LoginSignup
6
6

More than 5 years have passed since last update.

SendGrid+Ruby+UTF-8でメールを送信する

Last updated at Posted at 2014-10-31

クラウドメールサービスSendGridを使ってRubyからメールを送ってみます。
SendGridを使ってメールを送る方法はいくつかあります。詳しくは公式ブログを参照してください。

  • SMTP
  • Web API
  • マーケティングメール機能

今回はSMTPとX-SMTPAPIを組み合わせて宛先毎に内容の異なるメールを送ってみます。

SMTP

SMTPはWeb APIに比べて細かいメール送信パラメータを指定できるのがメリットですが、それが面倒な場合、デメリットにもなります。今回はUTF-8でメールを送ります。JISで送るバージョンはこちら

X-SMTPAPI

名前がSMTPっぽくて紛らわしいですが、X-SMTPAPIはSendGrid独自の拡張ヘッダです。これを利用するとメール送信時にSendGridの様々な機能を使うことができます。今回は、To、Substitution、Sectionを利用してメールの件名や本文内の特定のキー文字列を宛先毎に異なる値に置換してメールを送ってみます。

とりあえず送ってみる

以下の手順でサンプルコードをクローン、.envファイル編集、実行してください。
Rubyは2.1.0で動作確認しています。

git clone https://github.com/SendGridJP/sendgrid-smtp-ruby-example.git
cd sendgrid-smtp-ruby-example
cp .env.example .env
# .envファイルを編集してください
bundle install
ruby -f sendgrid-smtp-utf8.rb

.envファイルの編集

SENDGRID_USERNAME=SendGridユーザ名
SENDGRID_PASSWORD=SendGridパスワード
TOS=you@youremail.com,friend1@friendemail.com,friend2@friendemail.com
FROM=you@youremail.com

SENDGRID_USERNAME:SendGridのユーザ名を指定してください。
SENDGRID_PASSWORD:SendGridのパスワードを指定してください。
TOS:宛先をカンマ区切りで指定してください。
FROM:送信元アドレスを指定してください。

指定したアドレスにメールは届きましたか?

コード

# -*- encoding: utf-8 -*-
require 'mail'
require 'dotenv'
require 'smtpapi'

Dotenv.load
sendgrid_username = ENV["SENDGRID_USERNAME"]
sendgrid_password = ENV["SENDGRID_PASSWORD"]
from = ENV["FROM"]
tos = ENV["TOS"].split(',')

# smtpapi
smtpapi = Smtpapi::Header.new
smtpapi.set_tos(tos)
smtpapi.add_substitution("fullname", ["田中 太郎", "佐藤 次郎", "鈴木 三郎"])
smtpapi.add_substitution("familyname", ["田中", "佐藤", "鈴木"])
smtpapi.add_substitution("place", ["office", "home", "office"])
smtpapi.add_section('office', '中野')
smtpapi.add_section('home', '目黒')
smtpapi.add_category('Category1')

mail = Mail.new(:charset => "UTF-8") do
  from from
  to tos
  subject "[sendgrid-smtp-ruby-example] フクロウのお名前はfullnameさん"
  add_file "./gif.gif"
end
mail["x-smtpapi"] = smtpapi.to_json

text_plain = Mail::Part.new do
  body "familyname さんは何をしていますか?\r\n 彼はplaceにいます。"
  content_type "text/plain; charset=UTF-8"
end
text_html = Mail::Part.new do
  body "<strong> familyname さんは何をしていますか?</strong><br />彼はplaceにいます。"
  content_type "text/html; charset=UTF-8"
end
mail.part :content_type => "multipart/alternative" do |p|
  p.html_part = text_plain
  p.text_part = text_html
end

mail.delivery_method(:smtp,
  address: "smtp.sendgrid.net",
  port: 587,
  domain: "gmail.com",
  authentication: :login,
  user_name: sendgrid_username,
  password: sendgrid_password
)
mail.deliver

基本的にはJISバージョンほぼ同じですが、文字コードの変換周りがなくなり少しスッキリと書けました。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6