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

How to use Python to manage email automatically

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to manage email automatically with Python". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to manage email automatically with Python".

If you don't have time to read it, you need to know at least the following concepts

In order to reflect versatility, this time we will change to another mailbox to explain. The following cases all take 88 perfect mailbox as an example. This article will be divided into the following two parts.

Imbox receives email

Openpyxl writes to Excel file

Case one

"save the information about all the emails in the mailbox to Excel for backup

"to solve this requirement, we first use the keyring library to store the password (authorization code) obtained after enabling the IMAP/SMTP service locally in advance through the system key ring. First, open the command line and enter python:

Import keyring keyring.set_password ("88mail", "test@88.com", "password")

In this way, the password is stored locally, and then all you need is keyring.get_password to get it as a variable:

Import keyring password = keyring.get_password ('88 mailboxes, 'test@88.com')

Open the web version of the 88 mailbox to further confirm whether the configuration is complete, and the server mailbox:

The code to read the message with imbox is as follows:

Import keyring from imbox import Imbox password = keyring.get_password ('88 mailboxes, 'test@88.com') with Imbox (' imap.88.com', 'test@88.com', password, ssl=True) as imbox: # get all mail all_inbox_messages = imbox.messages () # get all mail for uid Message in all_inbox_messages: print (uid) # Mail number print (message.sent_from) # Sender print (message.subject) # message subject print (message.date) # date print (message.body ['plain']) # message text format body print (message.attachments) # attachment

There are a few things to note about the above code:

Imbox ('imap.qq.com',' xxx@qq.com', password, ssl=True) code needs to fill in the server, username mailbox, password, SSL encryption

The uid parameter in the body of the loop is the number of each message, which is very important and can be used to mark and delete messages.

Message.sent_from returns a list of parcel dictionaries with two keys: name and email,name are usernames (or nicknames), and email is the sender's mailbox

The string content obtained by message.date, such as' Tue, 3 Nov 2020 08:08:16 + 0800 (GMT+08:00)', a time in GMT format, we need to convert it to a normal date (year, month, day) + time (hours, minutes and seconds), that is, to convert the string in GMT time format to datetime type, you can use the following code:

Import datetime date = 'Tue, 3 Nov 2020 08:08:16 + 0800 (GMT+08:00)' GMT_FORMAT ='a,% d% b% Y% H:%M:%S + 0800 (GMT+08:00) 'print (datetime.datetime.strptime (date, GMT_FORMAT)) # 2020-11-03 08:08:16

It is also important to note that

The message.body ['plain'] body is returned as a list of strings

An example of message.attachments output is as follows:

[{'content-type':' application/x-zip-compressed', 'size': 1160851,' content':, 'filename':' xxxx.zip'}]

Is also a dictionary list, an attachment is a dictionary, including content-type size content filename 4 keys, namely type, size, content, file name. Return an empty list if there are no attachments.

With the above knowledge, we can re-parse the key information of the email into a string for easy storage:

Import keyring from imbox import Imbox import datetime password = keyring.get_password ('88 mailboxes, 'test@88.com') with Imbox (' imap.88.com', 'test@88.com', password, ssl=True) as imbox: all_inbox_messages = imbox.messages () # get all mail for uid Message in all_inbox_messages: name = message.sent_from [0] ['name'] # Sender name email = message.sent_from [0] [' email'] # Sender mailbox title = message.subject GMT_FORMAT ='a,% d% b% Y% H:%M:%S + 0800 (GMT+08:00) 'email_datetime = str (datetime.datetime.strptime (message.date) GMT_FORMAT)) email_date = email_datetime.strip () [0] # send date email_time = email_datetime.strip () [1] # send time text = message.body ['plain'] # text format body attachment_lst = [] attachments =''if message.attachments: for attachment in message.attachments: Attachment_lst.append (attachment ['filename']) attachments =' '.join (attachment_lst) print (uid, name, email, title, email_date, email_time) print (text, attachments if attachments else 'none')

Then use openpyxl to write the above information. First, create a table header at the beginning of the program to clarify the stored information:

From openpyxl import Workbook workbook = Workbook () # create a new workbook sheet = workbook.active heading = ['email name', 'sender name', 'sender mailbox', 'delivery date', 'delivery time', 'message body', 'attachment'] sheet.append (heading)

Later, as the message traverses, the content can be written to the table. The complete code for case 1 is as follows:

Import keyring from imbox import Imbox import datetime from openpyxl import Workbook workbook = Workbook () # create a new workbook sheet = workbook.active heading = ['email name', 'sender name', 'sender mailbox', 'delivery date', 'delivery time', 'message body', 'attachment'] sheet.append (heading) password = keyring.get_password ('88mailbox,' test@88.com') with Imbox ('imap.88.com') 'test@88.com', password, ssl=True) as imbox: all_inbox_messages = imbox.messages () # get all email for uid, message in all_inbox_messages: name = message.sent_from [0] [' name'] # Sender name email = message.sent_from [0] ['email'] # Sender email title = message.subject GMT_FORMAT ='% a D b Y H:%M:%S + 0800 (GMT+08:00) 'email_datetime = str (datetime.datetime.strptime (message.date) GMT_FORMAT)) email_date = email_datetime.strip () [0] # send date email_time = email_datetime.strip () [1] # send time text = message.body ['plain'] # text format body attachment_lst = [] attachments =''if message.attachments: for attachment in message.attachments: Attachment_lst.append (attachment ['filename']) attachments =' '.join (attachment_lst) sheet.append ([title, name, email, email_date, email_time, text, attachments]) workbook.save ('xxxxx.xlsx')

Case two

"back up all messages sent by xiaoming@qq.com in your inbox to Excel, and then delete them

"in fact, if you successfully understand case 1, then this case is very simple. From the above case, we know that the sender's email can be obtained through the following code:

With Imbox ('imap.88.com',' test@88.com', password, ssl=True) as imbox: all_inbox_messages = imbox.messages () for uid, message in all_inbox_messages: email = message.sent_from [0] ['email'] # Sender mailbox

Then you only need to judge if email = = 'xiaoming@qq.com' on this basis and you can execute the corresponding code later. In addition, the email is deleted based on the mailbox number uid, the code is imbox.delete (uid), and the specific code is an example:

For uid, message in all_inbox_messages: if email that meets certain conditions: imbox.delete (uid)

Then, by combining the above two knowledge points and the knowledge extension of case 1, it is easy to write the code of case 2:

Import keyring from imbox import Imbox import datetime from openpyxl import Workbook workbook = Workbook () sheet = workbook.active heading = ['email name', 'Sender name', 'Sender mailbox', 'date of delivery', 'time of delivery', 'message body', 'attachment'] sheet.append (heading) password = keyring.get_password ('88mailbox,' test@88.com') with Imbox ('imap.88.com',' test@88.com', password Ssl=True) as imbox: all_inbox_messages = imbox.messages () for uid, message in all_inbox_messages: email = message.sent_from [0] ['email'] if email = =' xiaoming@qq.com': # determine here the sender name = message.sent_from [0] ['name'] title = message.subject GMT_FORMAT ='% a D b Y H:%M:%S + 0800 (GMT+08:00) 'email_datetime = str (datetime.datetime.strptime (message.date) GMT_FORMAT)) email_date = email_datetime.strip () [0] email_time = email_datetime.strip () [1] text = message.body ['plain'] attachment_lst = [] attachments =''if message.attachments: for attachment in message.attachments: attachment _ lst.append (attachment ['filename']) attachments =' '.join (attachment_lst) sheet.append ([title, name, email, email_date, email_time, text, attachments]) imbox.delete (uid) # delete messages that meet the requirements here workbook.save ('xxxxx.xlsx')

Case three

"back up messages with" bonus "in the title of your inbox to Excel, and then mark these messages with a red flag

"the basic idea is similar to case 2, but start talking more and review only two knowledge points. to determine whether the title has the word" bonus ":

With Imbox ('imap.88.com',' test@88.com', password, ssl=True) as imbox: all_inbox_messages = imbox.messages () for uid, message in all_inbox_messages: title = message.subject if 'bonus' in title: pass

Red flag mail also deletes mail, which is also based on mailbox number uid. Examples of specific codes:

For uid, message in all_inbox_messages: if email that meets certain conditions: imbox.mark_flag (uid)

Therefore, the complete code of case 3 is as follows:

Import keyring from imbox import Imbox import datetime from openpyxl import Workbook workbook = Workbook () sheet = workbook.active heading = ['email name', 'Sender name', 'Sender mailbox', 'date of delivery', 'time of delivery', 'message body', 'attachment'] sheet.append (heading) password = keyring.get_password ('88mailbox,' test@88.com') with Imbox ('imap.88.com',' test@88.com', password Ssl=True) as imbox: all_inbox_messages = imbox.messages () for uid, message in all_inbox_messages: title = message.subject if 'bonus' in title: # determine whether the title contains the specified content name = message.sent_from [0] ['name'] email = message.sent_from [0] [' email'] GMT_FORMAT ='% a D b Y H:%M:%S + 0800 (GMT+08:00) 'email_datetime = str (datetime.datetime.strptime (message.date) GMT_FORMAT)) email_date = email_datetime.strip () [0] email_time = email_datetime.strip () [1] text = message.body ['plain'] attachment_lst = [] attachments =''if message.attachments: for attachment in message.attachments: attachment _ lst.append (attachment ['filename']) attachments =' '.join (attachment_lst) sheet.append ([title, name, email, email_date, email_time, text, attachments]) imbox.mark_flag (uid) # Mark the mail workbook.save ('xxxxx.xlsx') that meets the requirements here I believe you have a deeper understanding of "how to use Python to automate email management". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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