python使用imap-tools模块下载邮件附件的示例
imap-tools模块是python的第三方扩展, 它使用标准库imaplib,并将常见的邮件处理事件封装,邮件处理起来代码短,下面给大家介绍下python使用imap-tools模块下载邮件中的附件示例代码,感兴趣的朋友一起看看吧
最近在做一些email相关的办公自动化项目,发现一个第三方模块imap-tools不错, 网上没有啥相关介绍,所以记录下来.
环境: python3.8; imap-tools 0.39.0
需要pip 安装一下imap-tools模块
imap-tools模块是python的第三方扩展, 它使用标准库imaplib,并将常见的邮件处理事件封装,邮件处理起来代码短. 下面是个下载邮件附件的示例
1 2 3 4 5 6 7 8 9 10 | from imap_tools import MailBox with MailBox( "imap服务器名" ).login( "账号" , "密码" ) as mailbox: for msg in mailbox.fetch(limit = 2 ,reverse = True ): # 我这里为了避免读取全部的邮件,加上了limit=2的匹配参数,读取两封邮件,按照最新接收的次序排序,进行测试; for att in msg.attachments: # msg为上一行取得的全部邮件 if att.filename: # 如果附件的文件名不为空 att_data = att.payload # 获得附件的内容 f = open (att.filename, 'wb' ) # 用二进制打开,一般邮件附件都是二进制的. f.write(att_data) f.close() |
就是这么短,用起来比imaplib爽多了.
补充:使用Python的imap和email模块读取邮件
SMTP发送邮件的博文很多,但完整读取邮件的较少,本文主要是Python3读取邮件的编码,同时使用BeautifulSoup解析邮件内容。
Python版本信息,如下:
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import email import imaplib from bs4 import BeautifulSoup def main(): try : # 填写需要读取邮件服务器的imap的host和port,不知道请联系管理员 conn = imaplib.IMAP4_SSL(host = 'imap.xxx.com' , port = '993' ) # 读取邮件的用户名和密码 conn.login( 'xxx@qq.com' , 'your password' ) # 默认选择收件箱 INBOX conn.select() # Recent\Seen参数不起作用,暂先读取所有邮件 status, data = conn.search( None , 'ALL' ) if status ! = 'OK' : raise Exception( '读取邮件发生错误' ) emailids = data[ 0 ].split() # 倒序读取邮件 mail_counts = len (emailids) for i in range (mail_counts - 1 , 0 , - 1 ): # 获取邮件信息 status, edata = conn.fetch(emailids[i], '(RFC822)' ) # Message对象 msg = email.message_from_bytes(edata[ 0 ][ 1 ]) # 标题 subject = email.header.decode_header(msg.get( 'subject' )) # subject包含文档编码 default_code = subject[ 0 ][ 1 ] # print('Content_Type', msg.get_content_type()) ctype = msg.get_content_type() # 是否multipart类型,分别处理 if msg.is_multipart(): pl = msg.get_payload() for m in pl: ctype = m.get_content_type() if 'html' in ctype: # 注意decode参数,如果是True将解码base64/quoted-printable等格式编码内容,否则不解码 html = str (m.get_payload(decode = True ), m.get( 'content-type' ).split( '=' )[ 1 ]) # BeautifulSoup解析网页 soup = BeautifulSoup(html, "lxml" ) divs = soup.select( 'body' ) for d in divs: # 提取所有文本内容 text = d.get_text(strip = True ) print (text) else : html = str (msg.get_payload(decode = True ), default_code) # BeautifulSoup解析网页 soup = BeautifulSoup(html, "lxml" ) # 提取body标签里面的所有文本内容 divs = soup.select( 'body' ) for d in divs: text = d.get_text(strip = True ) print (text) except Exception as ex: print (ex) finally : # close conn.close() conn.logout() if __name__ = = "__main__" : main() |
到此这篇关于python使用imap-tools模块下载邮件中的附件的文章就介绍到这了
原文链接:https://www.cnblogs.com/worldinmyeyes/p/14587690.html
伪原创工具 SEO网站优化 https://www.237it.com/