次の例は、Nodejs を使用して SMTP 経由でメールを送信する方法を示しています。
// 以下のように nodemailer をロードします。
// npm install nodemailer --save
var nodemailer = require('nodemailer');
// SMTP トランスポートを使用して再利用可能なトランスポーターオブジェクトを作成します。
var transporter = nodemailer.createTransport({
"host": "smtpdm.aliyun.com",
"port": 25,
"secureConnection": true, // SSL を使用
"auth": {
"user": 'username@userdomain', // ユーザー名
"pass": 'xxxxxxx' // パスワード
}
});
// 注意!トランスポーターオブジェクトを再作成する必要はありません。すべて
// のメールに同じトランスポーターオブジェクトを使用できます。
// unicode 記号を使用してメールデータを設定します。
var mailOptions = {
from: 'NickName<username@userdomain>', // 送信者アドレス mailfrom はユーザーと同じである必要があります。
to: 'x@x.com, xx@xx.com', // 受信者のリスト
cc:'haha<xxx@xxx.com>', // 受信者のコピー
bcc:'haha<xxxx@xxxx.com>', // 受信者のシークレットコピー
subject: 'Hello', // 件名
text: 'Hello world', // プレーンテキスト本文
html: '<b>Hello world</b><img src="cid:01" style="width:200px;height:auto">', // html 本文
attachments: [
{
filename: 'text0.txt',
content: 'hello world!'
},
{
filename: 'text1.txt',
path: './app.js'
},{
filename:'test.JPG',
path:'./Desert.jpg',
cid:'01'
}
],
};
// 定義されたトランスポートオブジェクトでメールを送信します
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error);
}
console.log('Message sent: ' + info.response);
});