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 automatically manage Exchange mailbox

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces how to use Python automation to manage Exchange mailbox related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this article on how to automate the management of Exchange mailbox with Python will have a harvest, let's take a look.

Python is an interpretive, interactive, object-oriented programming language, which is not only simple, open source and portable, but also has rich official and third-party class libraries of Python. The underlying code of these libraries is not necessarily Python, and there are a lot of Cpicurus +. The code implemented in the C _ Cumber + language can be called in Python. So Python is also called "glue language". Based on the powerful class library of Python, we can achieve various functions such as Web development, automatic management, data analysis, machine learning and so on. What I'm going to show you today is how to use Python's Exchangelib library to easily automate the management of Exchange mailboxes. This paper focuses on the automated management of mail data in mailboxes and meeting schedules / calendars in Python.

Exchange is Microsoft's enterprise mail service system, and the latest local Exchange version is Exchange2019. With the continuous development of cloud services, the user base is becoming larger and larger. Many users switch to Exchange Online services or hybrid deployment of local Exchange and Exchange Online. The implementation code and cases in this article are applicable to both local Exchange and Exchange Online mailboxes.

Exchangelib is a powerful Exchange client Python library. It implements the object-relational mapping of Exchange mailboxes. The mailbox management operation of Exchangelib library is realized through EWS (Exchange Web Service). EWS is the interface service of Exchange mailbox. EWS integrates the functions of WebDAV and CODEX and is based on SOAP protocol. This allows it to be accessed remotely by any operating system that sends the HTTPS request. EWS is a very efficient Exchange resource access interface.

Before we begin, let's first run the command pip in CMD to install the Exchangelib library (pip is Python's package management tool): pip install exchangelib.

Next, import class libraries such as exchangelib and datetime:

The implementation of from exchangelib import Message,Credentials,Account,HTMLBody,Mailbox from exchangelib import EWSTimeZone,EWSDateTime import datetime as dt1.1 mail delivery is as follows: # assign the account number and password and other information of the mailbox to account credentials= Credentials ("", ") account= Account (', credentials=credentials,autodiscover=True) # html contains the email content in HTML format html = 'Hello worlletter' # configure information such as account header content recipient in message message = Message (account=account) Subject= "For Test", body=HTMLBody (html), to_recipients= (',),) # send mail message.send () 1.2.The implementation of message acquisition is as follows: # get local time zone tz = EWSTimeZone.localzone () # get the content of the message within a certain time period For example, get all the emails with a date of 3Universe 27Universe 2021. First specify the time zone, and then create an instance of the time date class related to the time zone. If the message is in a subfolder of the inbox Inbox, you can replace it with the name of the subfolder items = (account.inbox/''). All (). Filter (datetime_received__range= (dt.datetime (2021, 3, 27, 0, 0, 0, 0, tz), dt.datetime (2021, 3, 27, 23, 59, 59, 0, tz)) if you want to fetch the first 2021 messages You can use the following command: items = (account.inbox/'Reports'). All (). Order_by ('- datetime_received') [0all 100] 1.3 email forwarding is implemented as follows: items [0] .forward (subject='FWD:%s'%items [0] .subject, body=Items [0] .body, to_recipients= ('') ) 1.4 the implementation of mail deletion is as follows: items [0] .delete () # completely delete items [0] .soft _ delete () # soft delete recoverable to_folder = account.root/'Top of Information Store'/'Deleted Items' items [0] .move (to_folder) # move to the deleted folder

Through the above study, we know the basic method of operating Exchange mailbox through Python. Here is a simple example of managing mailboxes automatically: for example, to automatically reply to specific types of emails.

# get the most recent unread email today = dt.datetime.today () day = dt.timedelta (days=1) from_date = today-day tz = EWSTimeZone.localzone () tz_time = from_date.replace (tzinfo=tz) items = account.inbox.filter (is_read=False, datetime_received__gte=tz_time) # automatically reply to messages containing the specified header content from the specified user. Such as automatic instructions and so on. Filter_items = items.filter (subject__contains='xxx', sender='XXX@XXX.com') for item in Filter_items: Items [0] .conversation _ all (subject='', body='xxx')

Through Python, you can not only automate the operation of mail data, but also manage calendars, tasks, contacts, etc. Next, let's take a look at how to automate the management of the meeting calendar in your mailbox through Python. First, let's import the calendar-related module in Exchangelib. The CalendarItem class allows you to send a meeting request that you initiated or cancel a previously scheduled meeting. You can also process received MeetingRequest messages. You can reply to these messages using the AcceptItem, TentativelyAcceptItem, and DeclineItem classes.

The implementation of from exchangelib import CalendarItem from exchangelib.items import MeetingRequest, MeetingCancellation,SEND_TO_ALL_AND_SAVE_COPY2.1 meeting schedule creation is as follows: # EWSTimeZone.localzone () to obtain the local time zone information to facilitate the conversion of the date into the local time zone tz = EWSTimeZone.localzone () # CalenderItem information used to prepare the meeting schedule: such as start time and end time, topic, meeting invitation text Attendees, etc. Item = CalendarItem (account=account, folder=account.calendar, start=dt.datetime (2021, 4, 15, 11, 0, 0, 0, tz), end=dt.datetime (2021, 4, 15, 12, 0, 0, tz), subject= "For Test", body= "meeting test", required_attendees= ['xxx@xxx.com " ('xxx@xxx.com']) # item.save () is used to send a meeting invitation email item.save (send_meeting_invitations=SEND_TO_ALL_AND_SAVE_COPY) 2.1.The implementation of getting the meeting schedule is as follows: # for example, we need to get all the meeting schedules within a certain day calendars = account.calendar.all () .filter (dt.datetime (2021, 4, 14, 23, 59, 59, 0, tz), dt.datetime (2021) 4, 15, 23, 59, 59, 0, tz) # print out the title of the meeting schedule and view for calendar in calendars: print (calendar.subject) 2.2 the implementation of canceling the meeting schedule is as follows:

# cancel the schedule of the meeting titled 'For Test'. Cancel the command as "calendar.cancel ()". Calendar.subject.find () is used for keyword lookups to find the corresponding mail items.

For calendar in calendars: if calendar.organizer.email_address = = account.primary_smtp_address and calendar.subject.find ('For Test') > = 0: calendar.cancel () 2.2 automatically receives meeting invitations as follows:

# get the meeting invitation email by filtering the inbox email. Then for this type of mail, you can accept the meeting invitation, reject the meeting invitation, and temporarily accept the meeting invitation as follows. In Body, I can define the body content of the reply.

For item in items: if isinstance (item,MeetingRequest): item.accept (body= "Accpeted") # accept the meeting invitation item.decline (body= "sorry, I have no time") # reject the meeting invitation item.tentatively_accept (body= "I'll join if I'm free at that time") # temporarily accept the meeting invitation

In fact, the data in the Exchange mailbox, whether calendar or mail, is based on the folder structure. We can view the directory structure of the mailbox with the command "print (account.root.tree ())".

This is the end of the article on "how to automatically manage Exchange mailboxes with Python". Thank you for reading! I believe you all have a certain understanding of "how to use Python to automate the management of Exchange mailboxes". If you want to learn more, you are welcome to 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

Internet Technology

Wechat

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

12
Report