Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of python downloading email attachments using imap-tools Module

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about python using the imap-tools module to download email attachments example analysis, the editor thinks it is very practical, so share it with you to learn, I hope you can get something after reading this article, say no more, follow the editor to have a look.

Recently, I have been doing some email-related office automation projects. I found that a third-party module imap-tools is good, and there is no relevant introduction on the Internet, so record it.

Environment: python3.8; imap-tools 0.39.0

Pip is required to install the imap-tools module

The imap-tools module is a third-party extension of python. It uses the standard library imaplib and encapsulates common mail processing events. Here is an example of downloading email attachments

From imap_tools import MailBoxwith MailBox ("imap server name") .login ("account", "password") as mailbox: for msg in mailbox.fetch (limit=2,reverse=True): # in order to avoid reading all emails, I add the matching parameter of limit=2, read two emails, sort them according to the latest received order, and test them. For att in msg.attachments: # msg for all emails obtained on the previous line if att.filename: # if the file name of the attachment is not empty att_data = att.payload # get the contents of the attachment f = open (att.filename,'wb') # open it in binary, generally mail attachments are binary. F.write (att_data) f.close ()

It's so short, it's much better than imaplib.

Supplement: use Python's imap and email modules to read mail

There are many blog posts sent by SMTP, but few of them read the email completely. In this paper, Python3 reads the email code and uses BeautifulSoup to parse the email content.

Python version information, as follows:

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32

Code

Import emailimport imaplibfrom bs4 import BeautifulSoupdef main (): try: # enter the host and port of the imap that needs to read the mail server If you don't know, contact the administrator conn = imaplib.IMAP4_SSL (host='imap.xxx.com', port='993') # read the username and password of the email conn.login ('xxx@qq.com',' your password') # default inbox INBOX conn.select () # Recent\ Seen parameter does not work Read all messages status for now, data = conn.search (None, 'ALL') if status! =' OK': raise Exception ('error reading email') emailids = data [0] .split () # read messages in reverse order mail_counts = len (emailids) for i in range (mail_counts-1, 0 -1): # get email message status, edata = conn.fetch (emailids [I] '(RFC822)') # Message object msg = email.message_from_bytes (edata [0] [1]) # title subject = email.header.decode_header (msg.get ('subject')) # subject contains document encoding default_code = subject [0] [1] # print (' Content_Type' Msg.get_content_type () ctype = msg.get_content_type () # whether the multipart type Deal with if msg.is_multipart (): pl = msg.get_payload () for m in pl: ctype = m.get_content_type () if 'html' in ctype: # pay attention to the decode parameter If it is True, it will decode the base64/quoted-printable format and encode the content. Otherwise, html = str (m.get_payload (decode=True), m.get ('content-type'). Split (' =') [1]) # BeautifulSoup parsing web page soup = BeautifulSoup (html) will not be decoded "lxml") divs = soup.select ('body') for d in divs: # extract all text content text = d.get_text (strip=True) print (text) else Html = str (msg.get_payload (decode=True)) Default_code) # BeautifulSoup parsing web page soup = BeautifulSoup (html "lxml") # extract all the text content in the body tag 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 () above is the example analysis of python downloading email attachments using imap-tools module The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report