python邮件的发送与收取
时间: 2023-11-04 18:59:08 浏览: 40
发送邮件:
使用 Python 发送邮件可以使用内置的 smtplib 模块。以下是一个简单的示例:
```python
import smtplib
from email.mime.text import MIMEText
# 邮件内容
msg = MIMEText('这是一封测试邮件', 'plain', 'utf-8')
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['Subject'] = '测试邮件'
# 发送邮件
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_user = 'sender@example.com'
smtp_password = 'password'
with smtplib.SMTP(smtp_server, smtp_port) as smtp:
smtp.starttls()
smtp.login(smtp_user, smtp_password)
smtp.sendmail(smtp_user, [msg['To']], msg.as_string())
```
接收邮件:
使用 Python 接收邮件可以使用第三方库,例如 imapclient。以下是一个简单的示例:
```python
import imapclient
import pyzmail
# 连接邮箱
imap_server = 'imap.example.com'
imap_user = 'user@example.com'
imap_password = 'password'
with imapclient.IMAPClient(imap_server) as imap:
imap.login(imap_user, imap_password)
imap.select_folder('INBOX')
# 获取最新一封邮件
messages = imap.search(['ALL'])
latest_message_id = messages[-1]
raw_message = imap.fetch(latest_message_id, ['BODY[]'])[latest_message_id][b'BODY[]']
# 解析邮件内容
message = pyzmail.PyzMessage.factory(raw_message)
subject = message.get_subject().decode()
sender = message.get_addresses('from')[0][1]
body = message.text_part.get_payload().decode()
```