废话不多说,直接开始。
1.安装包
yarn add nodemailer
2.封装类
import * as nodemailer from 'nodemailer';
export class Emailer {
private transporter: nodemailer.Transporter;
constructor() {
this.transporter = nodemailer.createTransport({
host:'smtp.qq.com',
port:465,
secure:true,
auth:{
user:'发送方的qq邮箱',
pass:'密钥'
}
})
}
/**
* @function sendEmail 发送邮件
* @param to 接收方邮箱
* @param subject 邮件主题
* @param html 邮件内容
* @returns
*/
async sendEmail(to: string, subject: string, html: string) {
const mailOptions = {
from: cfg.email.auth.user,
to,
subject,
html,
};
return this.transporter.sendMail(mailOptions);
}
/**
* @function sendEmailWithAttachment 发送带附件的邮件
* @param to 接收方邮箱
* @param subject 邮件主题
* @param html 邮件内容
* @param attachment 附件
* @returns
*/
async sendEmailWithAttachment(to: string, subject: string, html: string, attachment: nodemailer.Attachment) {
const mailOptions = {
from: cfg.email.auth.user, // 发送方地址
to, // 接收方地址
subject, // 邮件主题
html, // 邮件内容
attachments: [attachment] // 附件
}
return this.transporter.sendMail(mailOptions);
}
}
然后就能直接使用了。