python接收郵件的幾種方式

Luckyzong發表於2019-04-13

1. 使用 poplib 元件

# -*- coding: utf-8 -*-

import poplib
from email import parser

host = 'pop.163.com'
username = 'mine@163.com'
password = '*******'

pop_conn = poplib.POP3_SSL(host)
pop_conn.user(username)
pop_conn.pass_(password)

#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]

# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]

#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
    print message['Subject']
pop_conn.quit()

 此方法會輸出收件箱所有內容。

2. 使用 imaplib 元件,檢測郵件並返回未讀郵件的數值

# -*- coding: utf-8 -*-

import imaplib,re

host = 'imap.163.com'
username = 'mine@163.com'
password = '*******'


def email_checker(username,password):

        i=imaplib.IMAP4_SSL('imap.163.com')
        try:
                i.login(username,password)
                x,y=i.status('INBOX','(MESSAGES UNSEEN)')
                messages=int(re.search('MESSAGES\s+(\d+)',y[0]).group(1))
                unseen=int(re.search('UNSEEN\s+(\d+)',y[0]).group(1))
                return (messages,unseen)
        except:
                return False,0

# Use in your scripts as follows:

messages,unseen = email_checker('mine@163.com','******')
print "%i messages, %i unseen" % (messages,unseen)

3. 使用 imaplib 元件,對未讀郵件內容整理,返回主題和內容

# -*- coding: utf-8 -*-

import imaplib
import email

def extract_body(payload):
    if isinstance(payload,str):
        return payload
    else:
        return '\n'.join([extract_body(part.get_payload()) for part in payload])

conn = imaplib.IMAP4_SSL("imap.163.com", 993)
conn.login("mine@163.com", "******")
conn.select()
typ, data = conn.search(None, 'UNSEEN')
try:
    for num in data[0].split():
        typ, msg_data = conn.fetch(num, '(RFC822)')
        for response_part in msg_data:
            if isinstance(response_part, tuple):
                msg = email.message_from_string(response_part[1])
                subject=msg['subject']                   
                print(subject)
                payload=msg.get_payload()
                body=extract_body(payload)
                print(body)
        typ, response = conn.store(num, '+FLAGS', r'(\Seen)')
finally:
    try:
        conn.close()
    except:
        pass
    conn.logout()

參考:https://justcoding.iteye.com/blog/918934

相關文章