プログラムからメールを送信する ¶
Node.js からメールを送信する例です。メールの送信には Nodemailer を使用します。次のコマンドで Nodemailer をインストールします。
$ npm install nodemailer --save
Nodemailer を使用してメールを送信する場合には、次のようなコードを使用します。
"use strict"; const nodemailer = require("nodemailer"); let account = { user: "[USER NAME HERE]", pass: "[USER PASSWORD HERE]" }; // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: "mx.mta.gis.gehirn.jp", port: 465, secure: true, // true for 465, false for other ports auth: { user: account.user, pass: account.pass } }); // setup email data with unicode characters let mailOptions = { from: "'Example Mailer ' <mail@example.gehirn.jp>", // sender address to: "example@gehirn.co.jp", // list of receivers subject: "テストメールです", // Subject line text: "これはテストです。", // plain text body html: "<b>これはテストです。</b>" // html body }; // send mail with defined transport object transporter.sendMail(mailOptions, (error, info) => { if (error) { return console.log(error); } console.log("Message sent: %s", info.messageId); });
このコード例は Nodemailer 公式サイト Example を Gehirn MTA の環境にあわせて編集したものです。