Python邮件解析:提取邮件内容与附件
使用Python解析邮件并提取内容和附件
想要用Python解析邮件并提取邮件内容和附件?这篇文章提供了使用Python 'email'库的详细代码示例,帮你轻松完成此任务。
import os
import email
import imaplib
import datetime
from email.header import decode_header
# 邮箱登录信息
username = 'your_email@example.com'
password = 'your_password'
imap_server = 'imap.example.com'
# 连接到IMAP服务器
imap = imaplib.IMAP4_SSL(imap_server)
imap.login(username, password)
imap.select('INBOX')
# 搜索邮件
status, messages = imap.search(None, 'ALL')
messages = messages[0].split()
for msg_id in messages:
# 获取邮件
status, data = imap.fetch(msg_id, '(RFC822)')
raw_email = data[0][1]
email_message = email.message_from_bytes(raw_email)
# 提取邮件内容
subject = decode_header(email_message['Subject'])[0][0]
from_ = decode_header(email_message['From'])[0][0]
to = decode_header(email_message['To'])[0][0]
date = decode_header(email_message['Date'])[0][0]
print('Subject:', subject)
print('From:', from_)
print('To:', to)
print('Date:', date)
# 提取附件
for part in email_message.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if filename:
filepath = os.path.join('attachments', filename)
if not os.path.isfile(filepath):
with open(filepath, 'wb') as f:
f.write(part.get_payload(decode=True))
print('Saved attachment:', filename)
# 关闭连接
imap.close()
imap.logout()
代码说明:
- 登录信息: 将'your_email@example.com'、'your_password'和'imap.example.com'替换为你的邮箱登录信息和IMAP服务器地址。
- 连接IMAP服务器: 使用
imaplib库连接到IMAP服务器。 - 搜索邮件: 搜索收件箱中的所有邮件。
- 获取邮件: 通过邮件ID获取邮件内容。
- 提取邮件信息: 使用
email.message_from_bytes解析邮件,并提取主题、发件人、收件人和日期等信息。 - 提取附件: 遍历邮件的各个部分,找到附件并保存到本地文件夹。
注意事项:
- 此代码仅适用于IMAP协议,如果使用POP3协议,需要使用
poplib库。 - 如果你的邮件服务器使用了其他安全协议,需要修改代码以适应。
希望这篇文章能够帮助你使用Python解析邮件并提取内容和附件!
原文地址: http://www.cveoy.top/t/topic/f3oo 著作权归作者所有。请勿转载和采集!