import imaplib
import email
from email.header import decode_header
import re
import pyperclip
import pyautogui
# QQ邮箱IMAP服务器信息
IMAP_SERVER = 'imap.qq.com'
IMAP_PORT = 993
# 邮箱用户名(QQ邮箱全地址)
USERNAME = '11XXXXXX71@qq.com'
# 生成的授权码
AUTHORIZATION_CODE = 'wrtcXXXXXXXujdec'
# 创建一个IMAP4_SSL对象并连接到服务器
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
# 使用邮箱地址和授权码登录邮箱
mail.login(USERNAME, AUTHORIZATION_CODE)
# 选择"inbox"邮件箱. 邮件箱名称不区分大小写
mail.select('inbox')
email_body=None
# 搜索最新一封邮件
status, email_ids = mail.search(None, 'ALL')
if status == 'OK':
# 取邮件ID列表中的第一个邮件ID,即最新邮件的ID
latest_email_id = email_ids[0].split()[-1]
# 获取邮件的RFC822数据(即整个邮件内容)
status, data = mail.fetch(latest_email_id, '(RFC822)')
# 确保邮件内容成功获取
if status == 'OK':
raw_email = data[0][1] # 获取原始邮件数据
msg = email.message_from_bytes(raw_email, policy=policy.default)
# 解析邮件内容
for part in msg.walk():
content_type = part.get_content_type()
if content_type == 'text/plain':
email_body = part.get_payload(decode=True).decode('utf-8')
break
elif content_type == 'multipart/related':
for subpart in part.walk():
if subpart.get_content_type() == 'text/html':
# Extract text from HTML
email_body = subpart.get_payload(decode=True).decode('utf-8')
# You can use BeautifulSoup or any other HTML parser to extract text from HTML
# Here, we simply print the raw HTML content
# print(email_body)
break
# 打印邮件正文106947
if email_body:
# 使用正则表达式匹配验证码模式,这里假设验证码是连续的6位数字,且前后都不是数字
# 在邮件正文中搜索验证码393384
match = re.search(r'\D(\d{6})\D', email_body)
# 如果找到验证码,则提取并打印
if match:
verification_code = match.group(1)
pyperclip.copy(verification_code)#提取的验证码复制到剪贴板
print(verification_code,"已复制到剪贴板,开始粘贴")
pyautogui.hotkey('ctrl', 'v') # Windows/Linux
else:
print('Verification code not found.')
# 关闭邮箱连接
mail.close()
mail.logout()
mail.logout()
返回结果
393384 已复制到剪贴板