nodemailer实现构建打包自动推送邮箱
# 运用nodemailer实现附件自动推送到邮箱 ⚡️
# 背景
有这样一个需求,当前端构建打包好后,leader希望能实现自动将压缩包发送到目标现场的邮箱中,免去研发手动发包给工程人员的步骤,从而提升研发效率。
# 先上图
# 方案
经过调用,网上有很多nodejs
的mailer
,但考虑再三后,决定使用 nodemailer
来解决该问题。
# 简介
Nodemailer是一个简单易用的Node.js邮件发送组件
官网地址:https://nodemailer.com
GitHub地址:https://github.com/nodemailer/nodemailer
Nodemailer的主要特点包括:
- 支持Unicode编码
- 支持Window系统环境
- 支持HTML内容和普通文本内容
- 支持附件(传送大附件)
- 支持HTML内容中嵌入图片
- 支持SSL/STARTTLS安全的邮件发送
- 支持内置的transport方法和其他插件实现的transport方法
- 支持自定义插件处理消息
- 支持XOAUTH2登录验证
# 实践
这里主要展示nodemailer核心配置,其它配置项可自行测试折腾
// 推送到项目负责人邮箱以部署
release(targetFile) {
// qiye.aliyun 邮箱 -> 163 邮箱
let transporter = nodemailer.createTransport({
// host: 'smtp.mxhichina.com',
service: 'qiye.aliyun',
port: 25, // SMTP 端口
secureConnection: true, // 使用了 SSL
auth: {
user: 'xxxx@zhitongits.com.cn',
// 优先smtp授权码,否则使用邮箱登录密码
pass: 'xxxxx',
}
});
// verify connection configuration
transporter.verify(function(error, success) {
if (error) { console.log(`* 验证邮箱服务: ${chalk.red("失败")}`, error); return; }
console.log(`* 验证邮箱服务: ${chalk.cyan("成功")}`);
});
let msgOptions = {
from: '"xxx" <xxxx@zhitongits.com.cn>', // sender address
to: 'xxxxx@163.com', // list of receivers
// cc: ['xxxx@163.com'], // 添加抄送人
// bcc: ['xxxx@163.com'], // 加密抄送人,收件人看不到
subject: "主题", // Subject line
// 发送text或者html格式
// text: 'Hello world?', // plain text body
html: '<b>请将附件下载后,部署到 /root/webapp 目录下 </b>', // html body
attachments: [
{
filename:"land.zip",
path: targetFile // 构建好后的压缩文件路径
}
]
};
// 163 邮箱 -> qiye.aliyun 邮箱
// let transporter = nodemailer.createTransport({
// // host: 'smtp.ethereal.email',
// service: '163', // 使用了内置传输发送邮件 查看支持列表:https://nodemailer.com/smtp/well-known/
// port: 465, // SMTP 端口
// secureConnection: true, // 使用了 SSL
// auth: {
// user: 'xxxx@163.com',
// // 设置smtp授权码,不是邮箱登录密码
// pass: 'xxxxx',
// }
// });
// let mailOptions = {
// from: 'xxxxx', // sender address
// to: 'xxx@qq.com', // list of receivers
// subject: "主题", // Subject line
// // 发送text或者html格式
// // text: 'Hello world?', // plain text body
// html: '<b>请将附件下载后,部署到 /root/webapp 目录下 </b>', // html body
// attachments: [
// {
// filename: `land.zip`,
// path: targetFile // 构建好后的压缩文件路径
// }
// ]
// };
// send mail with defined transport object
transporter.sendMail(msgOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log(`* 发版成功: ${chalk.cyan(targetFile)}`);
});
}
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77