Previously on Zero

Recently, when preparing automatic email monitoring, the company’s email address is Outlook, so there are two ways of automation. Please record here that has been used later

I. Usage of the Agreement

1.1 Overview of Mail Paths

1.1.1 Process of sending Emails

Sender — > MUA — > MTA — > Several MTA-MDA <- MUA <- recipient

For example, @163.com will be sent to NETEASE’s SERVER MTA, and then the service provider will deliver the Email to the server MDA storage of the other party. If the receiver of the Email is @sina.com, it will deliver the Email to Sina’s server MDA. If the other party wants to receive the message, it needs to extract the message from the corresponding MDA through the MUA.

The content of the email is actually stored on the MUA, which is what you see from the email software. To operate an email is to directly operate the contents on the MUA.

1.1.2 Email Overview

noun paraphrase
MUA Mail User AgentE-mail software, for exampleoutlook,foxmail
MTA Mail Transfer Agent, the mail transfer agent, i.eEmailService providers, such as netease and Sina
MDA Mail Delivery Agent, the mail delivery agent, which is the server of the service provider

1.1.3 Protocol Overview

With these concepts in mind, the essence of email is:

  • writeMUASend the email toMTA. The protocol used isSMTPThe agreement.
  • writeMUAfromMDAReceive mail.

When the email client sends emails, the SMTP server is configured first, that is, the MTA to which the emails are sent. If you are using @163.com, you can only and must send it to NETEASE’s MTA. Sina’s MTA does not serve netease’s users. To verify that you are a netease user, the SMTP server requires you to provide your email address and password.

1.2 Protocol Usage

Agreement, paraphrase
MIME Multipurpose Internet Mail extension type. A file with an extension is a type of file that can be opened by an application
SMTP Simple Mail Transfer ProtocolMail sending protocol a mail service based on FTP file transfer service.
POP Post Office Protocol, the current version is 3, commonly known asPOP3; Mail receiving protocol, this protocol is mainly used to support the use of clients to remotely manage emails on the server.
IMAP Internet Message Access ProtocolThe current version is 4. Interactive Mail access protocol. Its main function is that mail clients can obtain mail information from mail server through this protocol, download mail, and operate directlyMDAOn stored messages, such as from the inbox along with a garbage can.

1.2 the import

# # the pop protocol
import poplib ## Python built-in library

## Mail parsing
from email.parser import Parser Parse the original text of the message
from email.header import decode_header
from email.utils import parseaddr

# # the SMTP protocol
import smtplib

## Mail construction
from email.mime.text import MIMEText
Copy the code

1.3 the POP3 protocol

The POP3 protocol does not receive a readable message itself, but the original text of the message. The email module provides classes to parse the original text and turn it into a readable message object.

1.3.1 Logging In to the Mailbox

Base configuration
email_address = '[email protected]'
email_password = 'xxxx'
pop_server_host = 'partner.outlook.cn' ## Company level (Office365) link address, individual application may be different
pop_server_port = 995 # # port

## Login email
### Link to pop server
email_server = poplib.POP3_SSL(host=pop_server_host, port=pop_server_port, timeout=10)
email_server = poplib.POP3(host=pop_server_host, port=pop_server_port, timeout=10)

Verify that the mailbox exists
email_server.user(email_address)

Verify that the email password is correct
email_server.pass_(email_password)
Copy the code

1.3.2 Obtaining Emails

## Return the number of messages and space occupied
email_server.stat()

## Return message number
resp, mails, octets = email_server.list()

## Return the number of messages
index = len(mails)

## Get messages with a specific ordinal number, index starting at 1
resp, lines, octets = email_server.retr(index) ## lines Stores all information about the original text of the message.

Get the original text of the message
email_content = b'\r\n'.join(lines).decode('utf-8')

## Parse the message text
## resolves to a 'Message' object, in which case the object itself may be a 'MIMEMultipart' object that contains other 'MIME' objects nested, perhaps at more than one level.
content = Parser().parsestr(email_content) 
Copy the code

1.3.3 Deleting Emails and others

## Delete email
## Delete messages directly from the server using the message index number.
email_server.dele(index)

## Close the connection
email_server.quit()
Copy the code

1.4 the MIME parsing

MIME(Multipurpose Internet Mail Extensions): An Internet standard that describes message content types and can contain text, images, audio, video, and other application-specific data

MIME reference manual: www.w3school.com.cn/media/media…

1.4.1 MIME sample

Type/subtype extension
application/pdf pdf
image/jpeg jpe/jpg/jpeg

1.4.2 Mail Parsing

# # Suject parsing
## The Email Subject or Email contains the name of the encoded STR, in order to display normally, must decode.
def decode_str(s):
    value, charset = decode_header(s)[0] ## decode_header() returns a list of elements to cc multiple people. You can select the corresponding element using an index.
    if charset: ## charset is the encoding type obtained
        value = value.decode(charset)
    
    return value

Get the original text values of the corresponding elements, such as to and from
for header in ['From'.'To'.'Subject']
    content = content.get(header,' ')
    
# # the Subject
value  = decode_str(value) Header = 'Subject'
Copy the code
## From, To parse the sender, the recipient
hdr, addr = parseaddr(value) Header in ('From','To')
name = decode_str(hdr)
Copy the code
## Message body parsing
## The message text is also STR, need to check the encoding, otherwise non-UTF-8 encoding message will not be displayed properly
## Code confirmation
def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type'.' ').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
        
    return charset
    
## Text parsing
content_type = content.get_content_type()
if content_type = 'text/plain' or content_type = 'text/html':
    content_email = content.get_payload(decode=True)
    charset = guess_charset(content)
    if charset:
        content_email = content_email.decode(content)
Copy the code

1.5 the SMTP protocol

Python supports smtplib and email modules for SMTP. Email is responsible for building mail, and smtplib is responsible for sending mail.

1.5.1 Basic Usage

## Basic data
### Sender password Recipient server
from_addr = '[email protected]'
password = 'xxxx'
to_addr = '[email protected]'
smtp_server = 'smtp.163.com'

Build the base file
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name,'utf-8').encode(), addr))


msg = MIMEText('hello, send by Python... '.'plain'.'utf-8')
msg['From'] = _format_addr('name <%s>' % from_addr)
msg['To'] = _format_addr('name <%s>' % to_addr)
msg['Subject'] = Header('Greetings from SMTP... '.'utf-8').encode()

## Email send
server  = smtplib.SMTP(smtp_server,25) Server.starttls () server.starttls()
server.ser_debuglevek(1) Print all information about the initial interaction with the SMTP server
server.login(from_addr,password)
server.sendmail(from_addr, [to_addr], msg.as_string()) ## The message body is a STR as_string() that turns the MIMEText object into STR.
server.quit()
Copy the code

2. Configuration and usage

2.1 Configuration Usage – Applies only to Windows

The core of the configuration usage is to use the PyWin32 (Python for Windows) library to call the local Outlook configuration (Office provides COM interface based programming) for mail reading, but there is a problem that reading the configuration requires authorization. One is to invoke the authorization window for temporary authorization for a short time, and the other is to implement permanent authorization through background configuration.

2.2 the import

## pip install pywin32
import win32com
Copy the code

2.3 Basic Configuration

Start the Outlook process
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") ## Dispatch calls Outlook.application.

Get all accounts in the configuration
accounts = win32com.client.Dispatch("Outlook.Application").Session.Accounts

Get the level 1 directory
inbox = outlook.Folders(account.DeliveryStore.DisplayName)
folders = inbox.Folders
Copy the code