Node express OAuth 2.0 使用 nodemailer 套件透過 gmail 發送電子信箱

node 14.20.1

步驟

  1. 申請 Google 認證模式OAuth
    以上獲得
    • CLINENT_ID
    • CLINENT_SECRET
    • REFRESHTOKEN
    • ACCESSTOKEN
  2. 安裝nodemailer

一.申請 Google 認證模式OAuth

一.Google 更改認證模式,Nodemailer 官方文件 也推薦改使用 OAuth 2.0 來介接 Gmail

建立 OAuth
Console
Cloud Google

  1. 建立一個新專案 2.專案名 3.Api服務,搜尋Gmail Api 4.啟用Gmail Api 5.憑證->Auth 用戶端 ID 6選取外部 測試使用者 憑證 → 建立憑證 → OAuth 用戶端 ID
取得用戶端編號Client ID與用戶端密鑰Client Secret 網路應用程式 已授權的重新導向 URI」選擇「新增 URL」
https://developers.google.com/oauthplayground
取得 Refresh token 與 Access token

接下來請開啟這個網址這裡,然後點一下右上齒輪,並將「Use your own OAuth credentials」打勾輸入剛剛的 Client ID 以及 Client Secret



Step2 取得Token


以上獲得
  • CLINENT_ID
  • CLINENT_SECRET
  • REFRESHTOKEN
  • ACCESSTOKEN
加到環境變數內請三考

二.nodemailer:發信功能串接

安裝 nodemailer
nodemailer官網

1
npm install --save nodemailer 

新增一個頁面router

1
2
3
// routes
var contact = require('./routes/contact');
app.use('/contact', contact);

到contact 頁面

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');

//環境變數
require('dotenv').config()
router.get('/', (req, res)=> {
res.render('contact');
});
//這是寄送的成功訊息
router.get('/review', (req, res)=> {
res.render('contactReview');
});

//這是寄送的表單
router.post('/post', (req, res) =>
{
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: "OAuth2",
user: process.env.ACCOUNT,
clientId: process.env.GMAIL_CLINENT_ID,
clientSecret: process.env.GMAIL_CLINENT_SECRET,
refreshToken: process.env.GMAIL_CLINENT_REFRESHTOKEN,
accessToken: process.env.GMAIL_CLINENT_ACCESSTOKEN,
}
});
let mail = req.body.email;
var mailOptions = {
form: '"我自己"<xxx@gmail.com>',
to :`xxx@gmail.com,${mail}`,
subject:req.body.title+':'+req.body.username +'的訂單',
text: req.body.description
}
transporter.sendMail(mailOptions, (error, info) =>
{
console.log('info',info);
if(error){
return console.log(error,'訂單沒有送出!');
}
res.redirect('review');
})
});
module.exports = router;

token 有失效的問題

刷新令牌
刷新令牌2

// 完整程式碼https://github.com/hsiangfeng/node-nodemailer-finish
//https://hackmd.io/@yy933/Hy9rKyAE3?utm_source=preview-mode&utm_medium=rec

參考文獻
全端勇士之路 Node.js-OAuth 2.0 & nodemailer & Gmail
Send mails from Gmail using Nodemaile
Sending Emails with Node.js Using SMTP, Gmail, and OAuth2
Sending Emails with Node.js Using SMTP, Gmail, and OAuth2
Use Expressjs to send mails with gmail OAuth 2.0 and nodemailer
OAUTH2
Nodemailer/Gmail - What exactly is a refresh token and how do I get one?