
本文介绍使用 nodemailer 在 selenium 自动化测试项目中发送含 html/json/zip 测试报告附件的邮件,支持 gmail、outlook 等主流 smtp 服务,附完整配置示例与安全实践。
本文介绍使用 nodemailer 在 selenium 自动化测试项目中发送含 html/json/zip 测试报告附件的邮件,支持 gmail、outlook 等主流 smtp 服务,附完整配置示例与安全实践。
在自动化测试项目(如基于 Selenium + Node.js 的 E2E 测试套件)中,生成测试报告后自动邮件通知利益相关方(Stakeholder),是提升交付透明度与团队协作效率的关键环节。Nodemailer 是目前最成熟、轻量且稳定支持附件发送的 Node.js 邮件库,完全兼容各类 SMTP 服务商(Gmail、Outlook、企业邮箱等),并原生支持多格式附件(HTML 报告、JUnit XML、Allure ZIP、JSON 摘要等)。
✅ 快速接入步骤
-
初始化项目并安装依赖
Zenlink - Node SDK for ZenHeart下载ZenHeart zenlink 与 zenlink-mcp 为 OpenClaw,涵盖安装、MCP 注册、钩子接线、入站轮询及升级维护。
npm init -y npm install nodemailer
配置安全的 SMTP 连接(推荐使用 Gmail App Password)
⚠️ 注意:Gmail 账户需开启「两步验证」,并在 Google 账户设置中生成「应用专用密码」(App Password),切勿直接使用账户密码。
const nodemailer = require('nodemailer');
const fs = require('fs');
// 创建安全传输器(Gmail 示例)
const transporter = nodemailer.createTransporter({
service: 'gmail', // 或指定 host/port:host: 'smtp.gmail.com', port: 465, secure: true
auth: {
user: 'your-email@gmail.com',
pass: 'your-app-specific-password' // 替换为 16 位应用密码
}
});-
发送带附件的邮件(以 HTML 报告为例)
假设测试结束后生成了 report.html,可直接作为附件嵌入:
const mailOptions = {
from: '"Test Automation Team" <your-email@gmail.com>',
to: 'stakeholder@company.com',
subject: '✅ [AUTOMATION] Daily Test Report — ' + new Date().toLocaleDateString(),
html: `<h2>Hi Team,</h2>
<p>Attached is today's automated test execution report.</p>
<ul><li>Total Tests: <b>42</b></li><li>Passed: <b>38</b></li><li>Failed: <b>4</b></li></ul>
<p>— Generated by Selenium + Jest + Allure</p>`,
attachments: [
{
filename: 'test-report.html',
path: './reports/report.html', // 确保路径存在且可读
contentType: 'text/html'
},
{
filename: 'test-summary.json',
content: JSON.stringify({ passed: 38, failed: 4, duration: '2m 14s' }, null, 2),
contentType: 'application/json'
}
]
};
transporter.sendMail(mailOptions)
.then(info => console.log('Email sent successfully:', info.messageId))
.catch(err => console.error('Email sending failed:', err));⚠️ 关键注意事项
- 附件路径校验:发送前务必用 fs.existsSync() 校验文件是否存在,避免静默失败;
- 大文件处理:单附件建议 ≤ 25MB(Gmail 限制),超限时可压缩为 ZIP 或上传至云存储(如 AWS S3)后发送下载链接;
- 环境隔离:将邮箱凭证存于 .env 文件(配合 dotenv 加载),禁止硬编码或提交至 Git;
- 错误重试机制:生产环境建议封装重试逻辑(如 nodemailer-retry 中间件);
- 替代方案参考:若受企业防火墙限制无法直连 SMTP,可选用 SendGrid / Mailgun / Amazon SES — 它们均支持附件(需启用对应 API 权限并使用 nodemailer-sengrid 等适配器)。
通过以上配置,你即可在 afterAll() 或 CI/CD 流水线末尾(如 GitHub Actions 的 post-job)自动触发邮件报告,真正实现“测试完成 → 报告生成 → 邮件推送”闭环。

















