記錄下我用python登入騰訊企業郵箱收取郵件
一、要用python收取郵件先要會3個類
imaplib 用來收取郵件
imaplib 里面我們注意幾個方法:
login 使用明文密碼識別客戶端。該密碼將被引用。
select 選擇一個郵箱。返回的數據是郵箱中的郵件計數 (EXISTS響應)。默認郵箱是'INBOX'。如果 設置了只讀標志,則不允許對郵箱進行修改。
search 搜索郵箱以查找匹配的郵件
BeautifulSoup 用來解析 text/html 和 txet/plain 類型
email 用來解析郵件
email 里面的方法:
message_from_string 吧郵件轉換成字符串
walk 該walk()方法是一個通用的生成器,可用於以深度優先的遍歷順序迭代消息對象樹的所有部分和子部分。您通常將其walk()用作for循環中的迭代器; 每次迭代都返回下一個子部分。
get_content_type 返回郵件的內容類型
get_payload 返回當前的有效載荷,這將是一個列表 Message
二、擼代碼
from imaplib import IMAP4_SSL from smtplib import SMTP_SSL from bs4 import BeautifulSoup import email class AutoEmail:
def __init__(self): # 收件人 self.receiver = None # 發件人 self.sender = "郵箱賬號" self.host = '%s.exmail.qq.com' self.password = '授權碼' def ReceiverEmail(self):
# 連接騰訊企業郵箱的服務器 email_server = IMAP4_SSL(host=self.host % 'imap') # 登入郵箱 email_server.login(user=self.sender, password=self.password) # 選取一個郵箱 設置是否是只讀 inbox = email_server.select('INBOX', readonly=True) # 查找郵件 ALL 是所以郵件 status, emaillist = email_server.search(None, 'ALL')
emailist = emaillist[0].split() # 選取第幾封郵件 last = emailist[len(emailist) - 8] # 獲取消息 返回元組 狀態和消息主體 status, emaildata = email_server.fetch(last, '(RFC822)') # 轉換成Message對象 去解析 messages = email.message_from_string(emaildata[0][1].decode('utf-8')) # print(messages) import base64 for data in messages.walk(): # print(data.get_content_type()) if data.get_content_type() == 'text/plain': # print(data.get_payload())
charset = data.get_content_charset()
data = data.get_payload(decode=True).decode(charset)
print(data)
soup = BeautifulSoup(base64.b64decode(data.get_payload()), 'lxml').text
print(soup)
elif data.get_content_type() == 'application/octet-stream':
import re
if data.get('Content-Disposition', None):
Content_Disposition = data['Content-Disposition']
filename = re.search('filename="(.*)"$', Content_Disposition).group(1)
if filename.startswith('='):
filename_encode = re.match('=\?(.*)\?B', filename).group(1)
filename_base = re.search('B\?(.*)\?=$', filename).group(1)
filename_base64 = base64.b64decode(filename_base)
filename_decode = filename_base64.decode(filename_encode)
with open(filename_decode, 'wb') as file_base:
file_base.write(base64.b64decode(data.get_payload()))
if __name__ == '__main__':
autoemail = AutoEmail()
autoemail.ReceiverEmail()
算了不寫了,直接看的懂就行,太難調格式了,沒有道編輯方便
