テスト環境
- node.js v12
- nodemailer v6.3
サンプルコード
send-mail.js
varMailer=require('nodemailer')//// ローカルsmtpサーバ//constsmtp=Mailer.createTransport({host:'localhost',port:25})constmessage={// メッセージヘッダとかの設定// => メール受け取る側から見える情報from:'from@example.com',to:['to@example.com'],cc:['cc@example.com'],bcc:['bcc@example.com'],subject:'HELLO! nodemailer!!',text:'this is a test mail',html:'<p>this is a test mail</p>',// envelope: SMTPサーバー用の設定// FROM: (バウンスメールが届くアドレス)// envelope.from// と// RCPT TO: (実際に送信する宛先)// envelope.to, envelope.cc, envelope.bcc// 最終的には RCPT TO: へまとめられるので、// 実はどれかひとつに(例えば envelope.to) に// 全部まとめて書いてもいい// envelopeは "省略可能"// 省略した場合は以下のように自動付与されると思っていいenvelope:{from:'from@example.com',to:['to@example.com'],// RCPT TO: に突っ込まれるcc:['cc@example.com'],// RCPT TO: に突っ込まれるbcc:['bcc@example.com'],// RCPT TO: に突っ込まれる}// to:, cc: と bcc: はまとめてしまってもいいので以下だけでもOK// to: ['to@example.com','cc@example.com','bcc@example.com']}smtp.sendMail(message)
メッセージヘッダのfromとバウンスメールの受け取りアドレスを変えたい場合
例えば、MAILER-DAEMONが返ってきてしまった該当メールアドレスは無効化したいので、バウンスメール用のメールアドレスを用意して監視したい時などが利用場面です。
この場合は、envelopeを明示的に設定する必要あります。
envelopeを明示的に設定する場合、message.to, message.cc, message.bccに宛先を書くだけでは、メールは届かないので注意。
envelope.to, envelope.cc, envelope.bcc に宛先を書く必要がある。
constmessage={from:'from@example.com',to:['to@example.com'],cc:['cc@example.com'],// bcc: ['bcc@example.com'],// どうせ受取人には見えない箇所なので// envelope内にだけ、書いてしまってもよいsubject:'HELLO! nodemailer!!',text:'bounce-mails are sent to for-bounce@example.com ',html:'<p>bounce-mails are sent to for-bounce@example.com</p>',envelope:{from:'for-bounce@example.com',to:['to@example.com','cc@example.com','bcc@example.com']}}