以下对我有用,有两个部分:
01) app.js
02) Google 和 OAuth2 设置
app.js
var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: local_settings.my_gmail_username,
clientId: local_settings.my_oauth_client_id,
clientSecret: local_settings.my_oauth_client_secret,
refreshToken: local_settings.my_oauth_refresh_token,
accessToken: local_settings.my_oauth_access_token
}
});
var mail = {
from: "John Smith <me@mydomain.com>",
to: "user@userdomain.com",
subject: "Registration successful",
text: "You successfully registered an account at www.mydomain.com",
html: "<p>You successfully registered an account at www.mydomain.com</p>"
}
transporter.sendMail(mail, function(err, info) {
if (err) {
console.log(err);
} else {
// see https://nodemailer.com/usage
console.log("info.messageId: " + info.messageId);
console.log("info.envelope: " + info.envelope);
console.log("info.accepted: " + info.accepted);
console.log("info.rejected: " + info.rejected);
console.log("info.pending: " + info.pending);
console.log("info.response: " + info.response);
}
transporter.close();
});
Google 和 OAuth 设置
上面的代码需要如下设置:
01)转到https://console.developers.google.com
02)如果没有项目,会提示创建一个
03)点击Create Project
04)点击Create
05) 输入Project Name 并点击Create
06) 选择Gmail API
07)点击Enable
08)点击Create Credentials
09)输入需要的设置
10) 为 OAuth 客户端命名并确保将 https://developers.google.com/oauthplayground 添加为 redirect URI 以便稍后生成 refresh 和 access 令牌
11) 定义同意屏幕设置
12)点击I'll do this later和Done
13) 点击Edit 图标,查看您的Client ID 和Client Secret
14) 要生成access 和refresh 令牌,请转到https://developers.google.com/oauthplayground
15)点击右上角cog图标,勾选Use your own OAuth credentials并输入Client ID和Client Secret
16)在左栏中选择Gmail API v1并点击Authorise APIs
17)如果您登录了多个帐户,当提示时选择相关帐户
18)点击Allow
19)点击Exchange authorisation code for tokens
我不确定为什么access 令牌会倒计时,但希望屏幕底部的消息意味着令牌不会过期。