python 自动化:登录邮箱,获取邮件,解析并中文输出邮件正文。
完整代码,代码详解见附录
import email
import imaplib
from bs4 import BeautifulSoup
# 邮箱需要先进入安全设置将当前设备设置为受信任设备
# 登录前,需要设置为受信设备,否则如下不能登录。
# 创建 IMAP4_SSL 实例并登录
imap = imaplib.IMAP4_SSL("imap.qiye.aliyun.com")
#替换账号和密码
imap.login("xxx@xxxx.com", "xxxx")
imap.print_log()
# 选择邮件箱--邮件目录
imap.select('inbox')
# 搜索邮件
result, data = imap.uid('search', None, "ALL")
# 获取最新一封邮件
latest_email_uid = data[0].split()[-1]
# 获取邮件内容
result, email_data = imap.uid('fetch', latest_email_uid, '(RFC822)')
# 获取原始邮件内容并解码
raw_email = email_data[0][1]
raw_email = raw_email.decode()
# 解析邮件内容
message = email.message_from_string(raw_email)
for part in message.walk():
# 如果是纯文本或 HTML 邮件,则获取内容并解码 Unicode 编码
if part.get_content_type() == "text/plain" or part.get_content_type() == "text/html":
html_content = part.get_payload(decode=True).decode('utf-8')
soup = BeautifulSoup(html_content, 'html.parser')
texts = soup.get_text()
decoded_string = bytes(texts, 'utf-8').decode('unicode_escape')
print('******decoded_string', decoded_string)
break
附:代码分步解析
1、执行前,网页登录邮箱,添加设备为受信设备。
1.1、登录后,在邮箱设置中,查找收信服务器,如下图
设置 IMAP4_SSL 实例登录 目标服务器,
imap = imaplib.IMAP4_SSL("imap.qiye.aliyun.com")
import email
import imaplib
from bs4 import BeautifulSoup
# 邮箱需要先进入安全设置将当前设备设置为受信任设备
# 登录前,需要设置为受信设备,否则如下不能登录。
# 创建 IMAP4_SSL 实例并登录
imap = imaplib.IMAP4_SSL("imap.qiye.aliyun.com")
#替换账号和密码
imap.login("xxx@xxxx.com", "xxxx")
imap.print_log()
1.2 imap.login()中设置登录的邮箱账号和密码。
2、设置查找的邮箱文件夹 inbox,获取邮件并解析邮件内容。
# 选择邮件箱--邮件目录
imap.select('inbox')
# 搜索邮件
result, data = imap.uid('search', None, "ALL")
# 获取最新一封邮件
latest_email_uid = data[0].split()[-1]
# 获取邮件内容
result, email_data = imap.uid('fetch', latest_email_uid, '(RFC822)')
# 获取原始邮件内容并解码
raw_email = email_data[0][1]
raw_email = raw_email.decode()
# 解析邮件内容
message = email.message_from_string(raw_email)
3、将从html邮件内容中的获取邮件正文,设置为中文显示
for part in message.walk():
# 如果是纯文本或 HTML 邮件,则获取内容并解码 Unicode 编码
if part.get_content_type() == "text/plain" or part.get_content_type() == "text/html":
html_content = part.get_payload(decode=True).decode('utf-8')
soup = BeautifulSoup(html_content, 'html.parser')
texts = soup.get_text()
decoded_string = bytes(texts, 'utf-8').decode('unicode_escape')
print('******decoded_string', decoded_string)
break
以上完成,登录邮箱,获取邮件,解析并中文输出邮件正文。