python怎么实现邮件收发功能的代码
时间: 2024-03-13 22:43:27 浏览: 68
实现邮件收发功能的代码,需要使用 Python 的 `smtplib` 和 `email` 库。以下是一个简单的例子:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 发件人邮箱账号
sender = 'your_email@example.com'
# 发件人邮箱密码
password = 'your_email_password'
# 收件人邮箱账号
receiver = 'recipient_email@example.com'
# 创建邮件对象
msg = MIMEMultipart()
# 设置邮件主题、发件人、收件人
subject = 'Python Email Test'
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
# 添加邮件正文
body = 'This is a test email sent from Python.'
msg.attach(MIMEText(body, 'plain'))
# 添加附件
filename = 'test.txt'
with open(filename, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
# 发送邮件
try:
smtpObj = smtplib.SMTP('smtp.example.com', 25)
smtpObj.login(sender, password)
smtpObj.sendmail(sender, receiver, msg.as_string())
print('邮件发送成功')
except smtplib.SMTPException as e:
print('邮件发送失败:', e)
finally:
smtpObj.quit()
```
需要将 `your_email@example.com` 和 `your_email_password` 替换为实际的发件人邮箱地址和密码,将 `recipient_email@example.com` 替换为实际的收件人邮箱地址,将 `smtp.example.com` 替换为实际的 SMTP 服务器地址。此外,如果需要添加附件,需要将 `test.txt` 替换为实际的附件文件名。
阅读全文