自动化测试项目中带报告附件的邮件发送方案咨询
发送带附件的自动化测试报告邮件解决方案
一、编程语言原生/第三方库
Python 场景
- smtplib + email 标准库:Python自带,无需额外安装,直接通过SMTP协议发送,支持所有常见附件格式。
示例代码:
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders # 配置邮件基础信息 sender = "your_email@example.com" receivers = ["stakeholder1@example.com", "stakeholder2@example.com"] password = "你的邮箱密码或应用专用密码" subject = "自动化测试报告" body = "您好,附件是最新的自动化测试报告,请查收。" # 构建邮件对象 msg = MIMEMultipart() msg['From'] = sender msg['To'] = ", ".join(receivers) msg['Subject'] = subject # 添加邮件正文 msg.attach(MIMEText(body, 'plain')) # 加载并添加附件(以HTML测试报告为例) report_path = "test_report.html" with open(report_path, "rb") as f: attachment_part = MIMEBase('application', 'octet-stream') attachment_part.set_payload(f.read()) encoders.encode_base64(attachment_part) attachment_part.add_header('Content-Disposition', f"attachment; filename= {report_path}") msg.attach(attachment_part) # 连接SMTP服务器发送邮件 with smtplib.SMTP('smtp.example.com', 587) as server: server.starttls() server.login(sender, password) server.sendmail(sender, receivers, msg.as_string())
- yagmail:简化版SMTP库,代码更简洁,内置附件处理逻辑。
先安装:pip install yagmail
示例代码:
import yagmail # 初始化邮件客户端 yag = yagmail.SMTP(user='your_email@example.com', password='your_password', host='smtp.example.com') # 内容列表里直接加附件路径 email_contents = ["您好,附件是最新的自动化测试报告,请查收。", "test_report.html"] # 发送邮件 yag.send(to=['stakeholder1@example.com', 'stakeholder2@example.com'], subject='自动化测试报告', contents=email_contents)
Java 场景
- JavaMail API:Java官方邮件处理库,配合SMTP服务器即可发送带附件的邮件。
示例代码(简化实现):
import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; public class TestReportMailSender { public static void main(String[] args) { String senderEmail = "your_email@example.com"; String password = "your_password"; String recipient = "stakeholder@example.com"; String smtpHost = "smtp.example.com"; int smtpPort = 587; // 配置SMTP参数 Properties props = new Properties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", smtpPort); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); // 创建认证会话 Session session = Session.getInstance(props, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderEmail, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(senderEmail)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); message.setSubject("自动化测试报告"); // 构建多部分邮件(正文+附件) Multipart multipart = new MimeMultipart(); // 添加正文 BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText("您好,附件是最新的自动化测试报告,请查收。"); multipart.addBodyPart(bodyPart); // 添加附件 bodyPart = new MimeBodyPart(); String reportPath = "test_report.html"; DataSource source = new FileDataSource(reportPath); bodyPart.setDataHandler(new DataHandler(source)); bodyPart.setFileName(reportPath); multipart.addBodyPart(bodyPart); message.setContent(multipart); Transport.send(message); System.out.println("邮件发送成功"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
二、支持附件的第三方邮件服务
- Mailgun:API调用简单,支持批量发送带附件的邮件,适合中小规模项目。
- Amazon SES:企业级邮件服务,稳定性高,完全支持附件,有免费额度可供测试。
- Postmark:专注事务性邮件,投递率高,集成方便,支持多种附件格式。
补充:SendGrid其实支持附件发送
可能你之前的用法有误,用SendGrid Python SDK添加附件的示例如下:
import os import base64 from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType, Disposition # 构建基础邮件 message = Mail( from_email='your_email@example.com', to_emails='stakeholder@example.com', subject='自动化测试报告', html_content='<strong>您好,附件是最新的自动化测试报告,请查收。</strong>') # 读取并编码附件 with open('test_report.html', 'rb') as f: report_data = f.read() encoded_data = base64.b64encode(report_data).decode() # 创建附件对象 attachment = Attachment() attachment.file_content = FileContent(encoded_data) attachment.file_name = FileName('test_report.html') attachment.file_type = FileType('text/html') attachment.disposition = Disposition('attachment') message.attachment = attachment # 发送邮件 try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(f"发送成功,状态码: {response.status_code}") except Exception as e: print(f"发送失败: {e.message}")
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

