Nodemailer官网

nodemailer/nodemailer

1. Gmail直接登录法

或者两步验证开启后使用应用专用密码登录

126邮箱类似,但要在设置里开启客户端授权密码

Node.js Send an Email

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail@gmail.com',
pass: 'yourpassword'
}
});

var mailOptions = {
from: 'youremail@gmail.com',
to: 'myfriend@yahoo.com',
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);
}
});

2. Gmail使用SMTP服务器OAuth2登录

https://nodemailer.com/smtp/oauth2/#examples

token获取方式
Nodemailer/Gmail - What exactly is a refresh token and how do I get one?

Step 1: Obtain OAuth 2.0 credentials at Google Developers Console
获得Oauth的clientIdclientSecret
Step 2: Obtain the refresh token at Google OAuth2.0 Playground
获得refreshTokenaccessToken
查看具有帐号访问权限的第三方应用
https://myaccount.google.com/permissions
已经能访问Gmail

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var nodemailer = require('nodemailer');

let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
clientId: '18860796297-6tpjt9moo4rbptpipoq462c0uc7cqvsu.apps.googleusercontent.com',
clientSecret: '-HaMhhLnpDHt2dppuc8BUFWw'
}
});

var mailOptions = {
from: 'my-gamil-account@gmail.com',
to: 'friend-gamil-account@gmail.com',
subject: 'Sending Email using Node.js with XOAuth2',
text: 'That was easy!',
auth: {
user: 'my-gamil-account@gmail.com',
refreshToken: '1/m4HwkILnng_YlU2TGJGt8VYSLtTafkbVP6coOAeNcCw',
accessToken: 'ya29.GltHBg6nl8YiXlOMEa4CErjUpQssgbgQhc5dYqirQ8MgXhbe7K7Q6dBHuJU2GdWC6ZP5OH5CbOTnfPbtoebqTBGbEPNMX4xFiQ0FlZn-3zKDhnjMlJ3Iu6VAKySK',
// expires: 1484314697598
}
};

transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});