Nodemailer - Node.js

  • 作成日:
  • 最終更新日:2025/10/11

Nodemailer とは?

Node.js製のメール送信用モジュールでSMTPプロトコルを使ってメールを送信します。

HTMLメール、添付ファイル、複数宛先、CC/BCC などの機能があります。

開発中に便利な Ethereal Email との統合も可能。実際には送信されないですが Web で確認可能です。

Nodemailer をインストールするには、以下のコマンドを実行します。

npm install nodemailer

Gmail を使うには?

Gmail は通常、外部アプリからのログインをブロックします。アプリパスワードを使う設定が必用になります。

まず、「 2段階認証プロセス 」を有効にします。「 アプリ パスワード 」を作成し、表示された16桁のパスワードを控えます。このパスワードを Nodemailer の設定に使います。

以下のページから「 2段階認証プロセス 」を有効にする設定を行います。

アプリパスワードの設定については、以下のページを参考にしてください。「 アプリ パスワードを作成、管理する 」をクリックすると設定ページに移動します。

Ethereal Email用アカウントを生成して送信

const nodemailer = require('nodemailer');

async function sendTestEmail() {
  const testAccount = await nodemailer.createTestAccount();

  const transporter = nodemailer.createTransport({
host: testAccount.smtp.host,
port: testAccount.smtp.port,
secure: testAccount.smtp.secure,
auth: {
  user: testAccount.user,
  pass: testAccount.pass,
},
  });

  const info = await transporter.sendMail({
from: '"テスト送信者" <test@example.com>',
to: 'user@example.com',
subject: 'テストメール',
text: 'これはテストです。',
html: '<b>これはテストです。</b>',
  });

  console.log('メッセージID:', info.messageId);
  console.log('プレビューURL:', nodemailer.getTestMessageUrl(info));
}

sendTestEmail().catch(console.error);

Gmail SMTP を使った送信コード

const nodemailer = require('nodemailer');

async function sendGmail() {
  const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
  user: 'your.email@gmail.com',
  pass: 'your_app_password', // アプリパスワード16桁
},
  });

  const info = await transporter.sendMail({
from: '"テスト送信者" <your.email@gmail.com>',
to: 'recipient@example.com',
subject: 'Gmailからのテストメール',
text: 'これはGmail SMTPを使ったテストメールです。',
html: '<b>これはGmail SMTPを使ったテストメールです。</b>',
  });

  console.log('メッセージ送信完了:', info.messageId);
}

sendGmail().catch(console.error);

自前のSMTPサーバーに接続するための設定方法

const transporter = nodemailer.createTransport({
  host: 'mail.example.com',       // 自分のSMTPサーバー
  port: 587,                      // 通常は 587(STARTTLS)
  secure: false,                  // STARTTLSの場合は false、SSLなら true(ポート465)
  auth: {
user: 'noreply@example.com',  // SMTP認証用ユーザー
pass: 'your_smtp_password',   // パスワード
  }
});

よくあるSMTPポートとsecureの対応表は以下の通りです。

ポート番号 暗号化 secure の値 内容
25 なし false ISP によりブロックされる場合がほとんど
465 SSL/TLS true -
587 STARTTLS(推奨) false 推奨される設定