python收取邮件(腾讯企业邮箱)

记录下我用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()

  算了不写了,直接看的懂就行,太难调格式了,没有道编辑方便

猜你喜欢

转载自www.cnblogs.com/Xmz-selfi/p/11326545.html