pytest框架发送邮件代码
时间: 2023-09-04 16:06:42 浏览: 94
发送邮件的代码
我可以提供一份基于pytest框架的发送邮件的代码示例:
```
# 导入需要使用的库
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import pytest
# pytest测试函数
def test_send_mail():
# 邮件用户名和密码
mail_user = 'your_email_username'
mail_password = 'your_email_password'
# 邮件接收人列表
mail_receiver = ['receiver1@example.com', 'receiver2@example.com']
# 邮件主题
mail_subject = 'Test Mail'
# 邮件正文
mail_body = 'This is a test mail.'
# 构造邮件对象
message = MIMEMultipart()
# 添加邮件正文
message.attach(MIMEText(mail_body, 'plain', 'utf-8'))
# 添加附件
file_path = 'test_report.html'
with open(file_path, 'rb') as f:
att = MIMEApplication(f.read())
att.add_header('Content-Disposition', 'attachment', filename=file_path)
message.attach(att)
# 设置邮件头信息
message['From'] = mail_user
message['To'] = ';'.join(mail_receiver)
message['Subject'] = mail_subject
# 发送邮件
try:
smtp_server = 'smtp.example.com'
smtp_port = 465
server = smtplib.SMTP_SSL(smtp_server, smtp_port)
server.login(mail_user, mail_password)
server.sendmail(mail_user, mail_receiver, message.as_string())
server.quit()
print('Mail sent successfully!')
except Exception as e:
print('Error ocurred: ', str(e))
raise e
```
该函数会构造一个带附件的邮件对象,然后通过SMTP协议将邮件发送出去,其中需要填写发送邮箱的用户名、密码,SMTP服务器地址和端口等信息。同时,邮件正文和附件也需要自行设置。此处的事例中使用了pytest测试框架并将该代码放在了pytest测试函数中进行测试。
阅读全文