python 自动化-登录邮箱,验证系统发出邮件后,接收的邮件内容

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

以上完成,登录邮箱,获取邮件,解析并中文输出邮件正文。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值