python接收163邮箱邮件

import os
import email
import imaplib
import quopri
import requests
import re
from email.header import decode_header
import json
from pathlib import Path
project_dir = Path(__file__).resolve().parent

imap_host = "imap.163.com"


email_user = "thx2199@163.com"
email_pwd = "IMAP/SMTP服务授权码"


def download_file(url, target_directory=f"{project_dir}\\down"):
    # 构造目标文件路径
    file_name = url.split('=')[-1]
    target_path = os.path.join(target_directory, file_name)
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        os.makedirs(target_directory, exist_ok=True)
        with open(target_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        print(f"文件已成功下载到 {target_path}")
    else:
        print(f"下载失败,状态码:{response.status_code}")
        
        
imap_client = imaplib.IMAP4(imap_host)
imap_client.login(email_user, email_pwd)

# 解决网易邮箱报错:Unsafe Login. Please contact kefu@188.com for help
imaplib.Commands["ID"] = ('AUTH',)
args = ("name", email_user, "contact", email_user, "version", "1.0.0", "vendor", "myclient")
imap_client._simple_command("ID", str(args).replace(",", "").replace("\'", "\""))
mail_dir = imap_client.list()

# 获取邮箱目录。INBOX(收件箱)/Drafts(草稿箱)/Junk(垃圾箱)/Trash(已删除)/Sent Messages(已发送)
# 选择邮箱。返回的数据是中的消息数 信箱 (EXISTS 反应)。默认值信箱是'INBOX'
imap_client.select("INBOX")

# 在邮箱中搜索邮件。ALL(全部邮件),UNSEEN(未读邮件),SEEN(已读邮件)
# status:搜索结果状态
# messages:邮件的索引号
status, messages = imap_client.search(None, "ALL")

email_ids = messages[0].split()
for email_id in email_ids:
    status, msg_data = imap_client.fetch(email_id, '(RFC822)')
    for response_part in msg_data:
        if isinstance(response_part, tuple):
            
            msg = email.message_from_bytes(response_part[1])

            mail_subject, encoding = decode_header(msg["subject"])[0]
            if isinstance(mail_subject, bytes):
                mail_subject = mail_subject.decode(encoding if encoding is not None else 'utf-8')
            
            
            mail_from, encoding = decode_header(msg["from"])[-1]
            if isinstance(mail_from, bytes):
                mail_from = mail_from.decode(encoding if encoding is not None else 'utf-8')
                
            mail_date = msg['date']
            if mail_subject != '企业线索导出通知':
                continue
            
            # 邮件头部信息
            print(f'Subject: {mail_subject}')
            print(f'From: {mail_from}')
            print(f'Date: {mail_date}')
            
            # 解析邮件正文
            if msg.is_multipart():
                for part in msg.walk():
                    if part.get_content_type() == 'text/plain':
                        mail_content = part.get_payload(decode=True).decode()
                        # print(f'Content: {mail_content}')
            else:
                mail_content = msg.get_payload(decode=True).decode()
                # print(f'Content: {mail_content}')
            ret = re.search(r'下载链接:(.*\.csv)', mail_content)
            down_link = ret.group(1)
            # print(down_link)
            download_file(down_link)
posted @ 2024-09-09 14:50  anyiya  阅读(74)  评论(0编辑  收藏  举报