python 获取收件箱的具体信息

转自(https://stackoverflow.com/questions/2230037/how-to-fetch-an-email-body-using-imaplib-in-python)

通过邮件的用户信息和收件箱服务器信息 可以获取到收件箱的所有信息

代码详情

import datetime
import email
import imaplib


def readMail(i, data, mail):
    rangeList = list(range(i))
    for x in rangeList:
        try:
            latest_email_uid = data[0].split()[x]  # 最新的邮箱uid
            print("最新的uid:{}".format(latest_email_uid))
            result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')
            raw_email = email_data[0][1]  # bytes类型  邮件的所有内容
            raw_email_string = raw_email.decode('utf-8')  # 转换成utf-8
            email_message = email.message_from_string(raw_email_string)  # 邮箱的所有内容

            # Header Details
            date_tuple = email.utils.parsedate_tz(email_message['Date'])  # 获取邮箱的收到邮件时间
            if date_tuple:
                local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))  # 2018-10-22 14:55:02
                local_message_date = "%s" % (str(local_date.strftime("%a, %d %b %Y %H:%M:%S")))  # Mon, 22 Oct 2018 14:55:02
            email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))  # 发件人
            email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))  # 收件人
            subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))  # 邮件主题
            print(subject)

            # 邮件的文本内容
            for part in email_message.walk():
                if part.get_content_type() == "text/plain":
                    body = part.get_payload(decode=True)  # bytes类型
                    text = body.decode("utf-8")  # 转换成  utf-8类型
                    print(text)
        except Exception as e:
            # 可能发生错误  重新遍历取出
            rangeList.append(x)
            continue


def logginMail(EMAIL_ACCOUNT, PASSWORD, imapServer):
    mail = imaplib.IMAP4_SSL(imapServer)  # 链接邮箱服务器
    mail.login(EMAIL_ACCOUNT, PASSWORD)  # 登录邮箱
    mail.list()  # 邮箱列表
    mail.select('inbox')  # 选择收件箱
    result, data = mail.uid('search', None, "ALL")  # (ALL/UNSEEN)  # 查看邮箱列表
    if result == "OK":
        i = len(data[0].split())  # 收到的邮箱个数
        readMail(i, data, mail)
    else:
        print("获取邮箱列表失败:{}:{}".format(EMAIL_ACCOUNT, PASSWORD))


if __name__ == '__main__':
    imapServer = ""  # 收件箱服务器  imap.gmail.com
    EMAIL_ACCOUNT = ""  # 邮箱地址账号
    PASSWORD = ""  # 邮箱密码
    logginMail(EMAIL_ACCOUNT, PASSWORD, imapServer)

你可能感兴趣的:(工具类)