Python 接收邮件

Python 接收邮件

半成品代码,关键代码已经给出,若要使用需自行整理

import imaplib
import email
import poplib

connection = imaplib.IMAP4("imap.qq.com", imaplib.IMAP4_PORT)
connection.login("[email protected]", "mccgmqeaee")
connection.select("INBOX")
data = connection.search("utf-8", "seen")[1]
print(data[0].decode("utf-8"))


class MailReceiver:
    def __init__(self, address, password):
        self.address = address
        self.password = password
        self.connection = imaplib.IMAP4("imap.qq.com", imaplib.IMAP4_PORT)

    # 打开收件箱
    def open(self) -> bool:
        result = self.connection.login("[email protected]", "mcxhsyfqcgmqeaee")
        if result[0] == "OK":
            try:
                self.connection.select("INBOX")
                self.data_seen = connection.search("utf-8", "seen")[1][0].decode("utf-8")
                self.data_unseen = connection.search("utf-8", "unseen")[1][0].decode("utf-8")
                self.data_all = connection.search("utf-8", "all")[1][0].decode("utf-8")
            except imaplib.IMAP4.error:
                return False
        else:
            return False
        return True

    # 关闭收件箱
    def close(self):
        self.connection.close()
        self.connection.logout()

    # 获取未读消息,返回未读消息列表
    def get_unread_message(self):
        messages = []
        for num in self.data_unseen:
            status, msg_data = self.connection.fetch(num, '(RFC822)')
            message = email.message_from_bytes(msg_data)
            messages.append(message)
        return messages

    # 解析消息
    def parse(self, message):
        def parseHeader(message):
            """ 解析邮件首部 """
            subject = message.get('subject')
            h = email.Header.Header(subject)
            dh = email.Header.decode_header(h)
            subject = unicode(dh[0][0], dh[0][1]).encode('gb2312')
            # 主题
            print
            subject
            print
            '</br>'
            # 发件人
            print
            'From:', email.utils.parseaddr(message.get('from'))[1]
            print
            '</br>'
            # 收件人
            print
            'To:', email.utils.parseaddr(message.get('to'))[1]
            print
            '</br>'
            # 抄送人
            print
            'Cc:', email.utils.parseaddr(message.get_all('cc'))[1]

        def parseBody(message):
            """ 解析邮件/信体 """
            # 循环信件中的每一个mime的数据块
            for part in message.walk():
                # 这里要判断是否是multipart,是的话,里面的数据是一个message 列表
                if not part.is_multipart():
                    charset = part.get_charset()
                    # print 'charset: ', charset
                    contenttype = part.get_content_type()
                    # print 'content-type', contenttype
                    name = part.get_param("name")  # 如果是附件,这里就会取出附件的文件名
                    if name:
                        # 有附件
                        # 下面的三行代码只是为了解码象=?gbk?Q?=CF=E0=C6=AC.rar?=这样的文件名
                        fh = email.Header.Header(name)
                        fdh = email.Header.decode_header(fh)
                        fname = dh[0][0]
                        print
                        '附件名:', fname
                        # attach_data = par.get_payload(decode=True) # 解码出附件数据,然后存储到文件中

                        # try:
                        #     f = open(fname, 'wb') #注意一定要用wb来打开文件,因为附件一般都是二进制文件
                        # except:
                        #     print '附件名有非法字符,自动换一个'
                        #     f = open('aaaa', 'wb')
                        # f.write(attach_data)
                        # f.close()
                    else:
                        # 不是附件,是文本内容
                        print
                        part.get_payload(decode=True)  # 解码出文本内容,直接输出来就可以了。
                        # pass
                    # print '+'*60 # 用来区别各个部分的输出
        pass


'''

# status, msg_data = mbox.fetch(message_id, '(RFC822)')
# essage = email.message_from_bytes(msg_as_bytes)
def check_new_mail(self):
    try:
        server = imaplib.IMAP4_SSL(self.imap_server, self.imap_port)
        server.login(self.username, self.password)
    except:
        print("[!] Cannot connect imap server. Probably poor internet connection problem.")
        return -1

    server.select('INBOX')
    # server.search(None, 'unseen') returns ('OK', [b'818 819']) so
    new_mail = server.search(None, 'unseen')[1][0]
    new_mail = new_mail.decode("utf-8")

    # close & logout
    server.close()
    server.logout()

    # Means no new mail
    if len(new_mail) == 0:
        return 0

    new_mail = new_mail.split(' ')
    return len(new_mail)
'''

猜你喜欢

转载自blog.csdn.net/weixin_45792450/article/details/104134495