最近在做一些email相关的办公自动化项目,发现一个第三方模块imap-tools不错, 网上没有啥相关介绍,所以记录下来.

环境: python3.8; imap-tools 0.39.0

需要pip 安装一下imap-tools模块

imap-tools模块是python的第三方扩展, 它使用标准库imaplib,并将常见的邮件处理事件封装,邮件处理起来代码短. 下面是个下载邮件附件的示例

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

代码

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模块下载邮件中的附件的文章就介绍到这了,更多相关python下载邮件附件内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!