当前位置:宁波企业邮 » 企业目录 » 青岛 » 文章详细

python程序下载腾讯企业邮箱附件_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 importIMAP4_SSLfrom smtplib importSMTP_SSLfrom bs4 importBeautifulSoupimportemailclassAutoEmail:def __init__(self):#收件人

self.receiver =None#发件人

self.sender = "邮箱账号"self.host= ‘%s.exmail.qq.com‘self.password= ‘授权码‘

defReceiverEmail(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)

importbase64for data inmessages.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‘).textprint(soup)

elif data.get_content_type() == ‘application/octet-stream‘:importreif 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()

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



阅读:133
日期:2021-02-20

打印 】 【 关闭 】  【 字体: 】 
上一篇: 邮件客户端如何配置阿里云企业邮箱
下一篇: CentOS6使用postfix、extmail、Unix-Syslog等搭建企业邮箱
  >> 相关文章
 

服务热线

0574-55011290

微信二维码