LoginSignup
11
11

More than 5 years have passed since last update.

SendGrid+Node.js(nodemailer)+UTF-8でメールを送信する

Posted at

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

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

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

SMTP

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

X-SMTPAPI

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

とりあえず送ってみる

以下の手順でサンプルコードをクローン、.envファイル編集、実行してください。
Node.jsは0.10.28で動作確認していますが、nodemailerが動く程度の適度に古い環境であればたぶん動くと思います。

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

.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:送信元アドレスを指定してください。

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

コード

var dotenv = require('dotenv');
dotenv.load();

var sendgrid_username   = process.env.SENDGRID_USERNAME;
var sendgrid_password   = process.env.SENDGRID_PASSWORD;
var from                = process.env.FROM;
var tos                 = process.env.TOS.split(',');

var nodemailer = require('nodemailer');
var setting = {
  host: 'smtp.sendgrid.net',
  port: 587,
  requiresAuth: true,
  auth: {
    user: sendgrid_username,
    pass: sendgrid_password
  }
};
var mailer = nodemailer.createTransport(setting);

var smtpapi = require('smtpapi');
var header = new smtpapi();
header.setTos(tos);
header.addSubstitution('fullname', ['田中 太郎', '佐藤 次郎', '鈴木 三郎']);
header.addSubstitution('familyname', ['田中', '佐藤', '鈴木']);
header.addSubstitution('place', ['office', 'home', 'office']);
header.addSection('office', '中野');
header.addSection('home', '目黒');
header.addCategory('Category1');

var email = {
  from:     from,
  to:       tos,
  subject:  '[sendgrid-nodemailer-example] フクロウのお名前はfullnameさん',
  text:     'familynameさんは何をしていますか?\r\n 彼はplaceにいます。',
  html:     '<strong>familynameさんは何をしていますか?</strong><br />彼はplaceにいます。',
  headers:  {"x-smtpapi": header.jsonString()},
  attachments: [{
    path: './gif.gif'
  }]
};

mailer.sendMail(email, function(err, res) {
  mailer.close();
  if (err) {
    console.log(err);
  }
  console.log(res);
});
11
11
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
11
11