Node.jsメールを送信
Nodemailerモジュール
Nodemailerモジュールを使用すると、コンピューターから電子メールを簡単に送信できます。
Nodemailerモジュールは、npmを使用してダウンロードおよびインストールできます。
C:\Users\Your Name>npm install nodemailer
Nodemailerモジュールをダウンロードしたら、モジュールを任意のアプリケーションに含めることができます。
var nodemailer = require('nodemailer');
メールを送る
これで、サーバーからメールを送信する準備が整いました。
選択した電子メールプロバイダーのユーザー名とパスワードを使用して、電子メールを送信します。このチュートリアルでは、Gmailアカウントを使用してメールを送信する方法を説明します。
例
var nodemailer = require('nodemailer');
var transporter =
nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'yourpassword'
}
});
var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Sending Email using Node.js',
text:
'That was easy!'
};
transporter.sendMail(mailOptions,
function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
以上です!これで、サーバーは電子メールを送信できるようになります。
複数の受信機
複数の受信者に電子メールを送信するには、それらをmailOptionsオブジェクトの「to」プロパティにコンマで区切って追加します。
例
複数のアドレスに電子メールを送信します。
var mailOptions = {
from: 'youremail@gmail.com',
to: '[email protected],
[email protected]',
subject: 'Sending Email using Node.js',
text:
'That was easy!'
}
HTMLを送信する
電子メールでHTML形式のテキストを送信するには、「text」プロパティの代わりに「html」プロパティを使用します。
例
HTMLを含む電子メールを送信します。
var mailOptions = {
from: 'youremail@gmail.com',
to: '[email protected]',
subject: 'Sending Email using Node.js',
html:
'<h1>Welcome</h1><p>That was easy!</p>'
}