Python 使用zmail、imapclient或imap_tools接收邮件

Python中,可以使用通过代码方式接收邮件,本文主要介绍使用zmail、imapclient和imap_tools三种方法接收邮件,以及相关的示例代码。

1、使用zmail接收邮件

1)安装zmail

pip install zmail

2)使用代码

import zmail

mail_pass = '**********' # 使用的qq邮箱发送邮件,为qq邮箱的授权码,非密码,可在网页的邮箱设置中开通,其它邮箱也类似
server = zmail.server('cjavapy@qq.com', mail_pass)
# 获取最新的邮件 mail = server.get_latest() # 通过邮件id获取邮件 mail = server.get_mail(2) # 通过邮件 标题/日期/发送人 查找邮件 mail = server.get_mails(subject='GitHub',start_time='2018-1-1',sender='github') # 查找邮件并列出前10的邮件列表 mail = server.get_mails(subject='GitHub',start_time='2018-1-1',sender='github',start_index=1,end_index=10) # 获取邮箱信息,返回元组(邮件数目,邮箱大小) mailbox_info = server.stat() # Zmail中每一个邮件对应一个字典,通过如下方法获取邮件内容 subject = mail['subject'] # 显示邮件基础信息 mail = server.get_latest() zmail.show(mail) # 显示邮件的所有内容 mail = server.get_latest() for k,v in mail.items(): print(k,v) #验证SMTP和POP是否运转正常 #if server.smtp_able(): # pass # SMTP function. #if server.pop_able(): # pass # POP function.

2、使用imapclient接收邮件

1)安装imapclient

pip install imapclient

2)使用代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
 
from imapclient import IMAPClient
 
 
class Imapmail(object):
 
    def __init__(self):  # 初始化数据
        self.serveraddress = None
        self.user = None
        self.passwd = None
        self.prot = None
        self.ssl = None
        self.timeout = None
        self.savepath = None
        self.server = None
 
    def client(self):  # 链接
        try:
            self.server = IMAPClient(self.serveraddress, self.prot, self.ssl, timeout=self.timeout)
            return self.server
        except BaseException as e:
            return "ERROR: >>> " + str(e)
 
    def login(self):  # 认证
        try:
            self.server.login(self.user, self.passwd)
        except BaseException as e:
            return "ERROR: >>> " + str(e)
 
    def getmaildir(self):  # 获取目录列表 [((), b'/', 'INBOX'), ((b'\\Drafts',), b'/', '草稿箱'),]
        dirlist = self.server.list_folders()
        return dirlist
 
    def getallmail(self):  # 收取所有邮件
        print(self.server)
        self.server.select_folder('INBOX', readonly=True)  # 选择目录 readonly=True 只读,不修改,这里只选择了 收件箱
        result = self.server.search()  # 获取所有邮件总数目 [1,2,3,....] 
        #self.server.search(['FROM', 'cjavapy@qq.com'], charset='UTF-8')
        #self.server.search([u'SINCE', date(2022, 3, 14)])
        print("邮件列表:", result)
        for _sm in result:
            # data = self.server.fetch(_sm, ['ENVELOPE'])
            # size = self.server.fetch(_sm, ['RFC822.SIZE'])
            # print("大小", size)
            # envelope = data[_sm][b'ENVELOPE']
            # print(envelope)
            # subject = envelope.subject.decode()
            # if subject:
            #     subject, de = decode_header(subject)[0]
            #     subject = subject if not de else subject.decode(de)
            # dates = envelope.date
            # print("主题", subject)
            # print("时间", dates)
 
            msgdict = self.server.fetch(_sm, ['BODY[]'])  # 获取邮件内容
            mailbody = msgdict[_sm][b'BODY[]']  # 获取邮件内容
            with open(self.savepath + str(_sm), 'wb') as f:  # 存放邮件内容
                f.write(mailbody)
 
    def close(self):
        self.server.close()
 
 
if __name__ == "__main__":
 
    imap = Imapmail()
    imap.serveraddress = "imap.163.com"  # 邮箱地址
    imap.user = "xxxxxx"  # 邮箱账号
    imap.passwd = "xxxxx"  # 邮箱密码,QQ邮箱或其它邮箱,可能需要使用授权码
    imap.savepath = ""  # 邮件存放路径
    imap.client()
    imap.login()
    imap.getallmail()
    imap.close()
# 'Trash'   回收站邮件
# 'Spam'    垃圾邮件
# 'Sent'    已发送邮件
# 'Drafts'  草稿箱
# 'Archive' 存档
# 'INBOX'   收件箱

 3、使用imap_tools接收邮件 

1)安装imap_tools 

pip install imap-tools 

2)使用代码 

# 'Trash'   回收站邮件
# 'Spam'    垃圾邮件
# 'Sent'    已发送邮件
# 'Drafts'  草稿箱
# 'Archive' 存档
# 'INBOX'   收件箱
import datetime as dt
from imap_tools import MailBox, AND, OR, NOT

mail_pass = '**********' # 使用的qq邮箱发送邮件,为qq邮箱的授权码,非密码,可在网页的邮箱设置中开通,其它邮箱也类似

with MailBox('imap.mail.com').login('cjavapy@qq.com', mail_pass, 'INBOX') as mailbox:

    # 从收件箱文件夹中获取邮件主题列表
    subjects = [msg.subject for msg in mailbox.fetch()]

    # 将所有邮件从当前文件夹(INBOX)移动到folder2
    mailbox.move(mailbox.fetch(), 'INBOX/folder2')

    # 获取带有INBOX子文件夹名称的列表
    inbox_subfolders = [folder_info['name'] for folder_info in mailbox.folder.list('INBOX')]

    # 获取大量的电子邮件 (日期不在 (2020-1-1, 2020-1-2) 并标记,主题包含 "你好")
    criteria = AND(NOT(OR(date=[dt.date(2020, 1, 11), dt.date(2020, 1, 12)])), flagged=True, subject='你好')
    for msg in mailbox.fetch(criteria, charset='utf8'):
        body = msg.text or msg.html
    print(body)

参考文档:https://service.mail.qq.com/cgi-bin/help?subtype=1&&no=1001256&&id=28

推荐阅读
cjavapy编程之路首页