鱼C论坛

 找回密码
 立即注册
查看: 2467|回复: 1

[技术交流] 使用imaplib获取电子邮件正文和附件

[复制链接]
发表于 2019-11-28 03:47:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 XiaoPaiShen 于 2019-11-29 06:12 编辑

1.首先定义一个类: Email_Checker
在该类的构造方法中,创建邮件服务器并用邮件地址和密码登录。
选择 'inbox' 表示收件箱
2.在imap 协议下,邮件的正文可以有两种格式保存,'text/plain', 'text/html'
我将这两种格式保存在mail_content字典中,如果'text/plain'存在,就返回该值,否则返回'text/html'的值
3.mail_messages中保存了所有符合过滤条件的邮件

  1. import imaplib
  2. import email

  3. from email.header import decode_header
  4. class Email_Checker:
  5.     def __init__(self, email='', password='', server='imap.gmail.com'):
  6.         self.server = server
  7.         self.email = email
  8.         self.password = password
  9.         self.mail = imaplib.IMAP4_SSL(self.server)
  10.         self.mail.login(self.email, self.password)
  11.         self.mail.select('inbox')
  12.         self.mail_content = {'plain': None, 'html': None}
  13.         self.mail_messages = list()
复制代码

使用email.header中的decode_header方法进行解码,用于附件文件名可以有正确的显示
  1. def decode_content(self, content):
  2.         if not content:
  3.             return None
  4.         value, charset = decode_header(content)[0]
  5.         if charset:
  6.             value = value.decode(charset)
  7.         return value
复制代码

在imap 协议下,可以使用uid方法查找和提取邮箱中的message,
Using UIDs instead of volatile sequential ids
The imap search function returns a sequential id, meaning id 5 is the 5th email in your inbox.
That means if a user deletes email 10, all emails above email 10 are now pointing to the wrong email.
This is unacceptable.

Luckily we can ask the imap server to return a UID (unique id) instead.
The way this works is pretty simple: use the uid function, and pass in the string of the command in as the first argument. The rest behaves exactly the same.

Parsing Raw Emails
Emails pretty much look like gibberish. Luckily we have a python library for dealing with emails called… email.
It can convert raw emails into the familiar EmailMessage object.

  1. def filter_mails(self, title):
  2.         status, data = self.mail.uid('search', None, "ALL")
  3.         email_uids = data[0].split()
  4.         for uid in email_uids:
  5.             status, content = self.mail.uid('fetch', uid, '(RFC822)')
  6.             raw_email = content[0][1]
  7.             message = email.message_from_bytes(raw_email)
  8.             mail_subject = message['subject']

  9.             if mail_subject == title:
  10.                 self.mail_messages.append(message)
复制代码


下载附件
  1. def download_attachment(self, message):
  2.         for part in message.walk():
  3.             if part.get_content_maintype() == 'multipart':
  4.                 continue
  5.             if part.get('Content-Disposition') is None:
  6.                 continue

  7.             filename = part.get_filename()
  8.             filename = self.decode_content(filename)
  9.             print('FileName: ', filename)

  10.             if not filename:
  11.                 continue
  12.             
  13.             # save attachment            
  14.             with open(filename, 'wb') as attach:
  15.                 data = part.get_payload(decode=True)
  16.                 attach.write(data)  
  17.                 print("attachment {0} saved".format(filename))
复制代码


完整程序:
游客,如果您要查看本帖隐藏内容请回复


小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-5-21 08:01:01 From FishC Mobile | 显示全部楼层
很好的,解决了我的问题
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-24 01:26

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表