NodeJS Mail 套件
npm install nodemailer
nodemailer 封裝 Package code by TS
import nodemailer from 'nodemailer';
import { Options } from 'nodemailer/lib/smtp-transport';
export type SendMailOptions = nodemailer.SendMailOptions;
/**
* SMTP Client
*
* @export
* @class Smtp
*/
export class Smtp {
/** SMTP設定 */
private options: Options;
/** email 轉運器 */
private transporter: nodemailer.Transporter;
/**
*Creates an instance of Smtp.
* @param {string} account 帳號(寄件者信箱)
* @param {string} password 密碼
* @memberof Smtp
*/
constructor(account: string = process.env.SMTP_ACCOUNT, password: string = process.env.SMTP_PASSWORD) {
this.options = {
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: process.env.SMTP_PORT === 465 ? true : false,
tls: {
rejectUnauthorized: false,
}
};
if (account) {
this.options.auth = {
user: account,
pass: password
}
}
this.transporter = nodemailer.createTransport(this.options);
this.transporter.verify((error, success) => {
if (success) { console.log('Server is ready to take our message');}
else { console.log(error); }
});
}
/**
* 寄送mail
*
* @param {nodemailer.SendMailOptions} mail email內容
* @memberof Smtp
*/
async send(mail: SendMailOptions): Promise<boolean> {
const isSended: Promise<boolean> = new Promise((resolve) => {
this.transporter.sendMail(mail, (error, info) => {
if(error) {
console.log(`Error: ${error}`);
return resolve(false);
}
else {
console.log(`Email sent: ${info.response}`)
return resolve(true);
}
});
});
return isSended;
}
}
Gmail 設定
專案.env
的環境變數設定
#SMTP
SMTP_HOST=smtp.gmail.com
SMTP_PORT=465
SMTP_ACCOUNT=xxx.gmail.com
SMTP_PASSWORD=xxxpasword
由於是使用到 ap層控制 Gmail,所以Gmail本身的安全性要下降給 ap層去控制,要到自己的Gmail然後右上角的 齒輪 > 查看所有的設定 > 轉寄 和 POP/IMAP
將 IMAP 打開 儲存變更