python pytest框架发送邮件
时间: 2024-06-29 14:00:29 浏览: 199
Python的pytest是一个流行的单元测试框架,主要用于编写和运行测试代码,确保程序的正确性。如果你需要在pytest测试中发送电子邮件,通常会用到第三方库如`smtplib`(用于发送邮件的SMTP协议)或者更高级的库如`selenium-requests`(结合了requests和selenium的邮件功能)。然而,pytest本身并不直接支持邮件发送,它是专注于测试的。
以下是一个使用`smtplib`在pytest中发送简单邮件的基本示例:
```python
import smtplib
from email.mime.text import MIMEText
def test_send_email():
sender = "your-email@example.com"
receiver = "recipient-email@example.com"
password = "your-password" # 可以从环境变量或配置文件获取
subject = "pytest test email"
body = "This is a test email sent from pytest."
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
try:
server = smtplib.SMTP('smtp.example.com', 587) # 邮箱服务端
server.starttls() # 加密连接
server.login(sender, password)
server.sendmail(sender, receiver, msg.as_string())
server.quit()
print("Email sent successfully.")
except Exception as e:
print(f"Failed to send email: {e}")
# 在pytest中执行这个测试
def test_suite():
test_send_email()
```
要执行此测试,你需要在pytest命令行中运行:
```sh
pytest -v test_email.py
```
阅读全文