1. Introduction

Email, as the most formal form of communication, is often used in the daily business process

We all know that Python has built-in SUPPORT for SMTP for sending plain text, rich text, HTML, and more

This article looks at three ways to send mail in Python

2. Prepare

Take mailbox 126 as an example. Before coding, we need to enable SMTP service

Then, manually add an authorization code

The account, authorization code, and server address are used to log in to the email server

3. Method 1: SMtplib

Smtplib is a Python dependency library that can be directly imported and used. First, initialize an SMTP instance using the email account, authorization code, and email server address, and then connect to it

def __init__(self):
    # initialization
    self.smtp = smtplib.SMTP()

    # Connect to the email server address
    self.smtp.connect('smtp.126.com')

    # Add subject and attachment, body of message
    self.email_body = MIMEMultipart('mixed')

    # Sender address and authorization code
    self.email_from_username = '**@126.com'
    self.email_from_password = 'Authorization code'

# login
self.smtp.login(self.email_from_username, self.email_from_password)
Copy the code

Then, add the recipient list, message title, message body content, attachment path, and attachment file name to the message body defined above

def generate_email_body(self, email_to_list, email_title, email_content, attchment_path, files):
    ""Param email_to_list: recipient list: param email_title: email title: param email_Content: email body content: param attchment_path: attachment path :param files: file name list of attachments :return:"""
    self.email_body['Subject'] = email_title
    self.email_body['From'] = self.email_from_username
    self.email_body['To'] = ",".join(email_to_list)

    for file in files:
        file_path = attchment_path + '/' + file
        if os.path.isfile(file_path):
            # Build an attachment object
            att = MIMEText(open(file_path, 'rb').read(), 'base64'.'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att.add_header("Content-Disposition"."attachment", filename=("gbk"."", file))
            self.email_body.attach(att)

    text_plain = MIMEText(email_content, 'plain'.'utf-8')
    self.email_body.attach(text_plain)
Copy the code

You can then use the SMTP instance object to send the message out

  # To List
email_to_list = ['Address of Recipient 1'.'Recipient 2 address']

# Send email
Note: both the sender and the recipient must be specified, otherwise it will be treated as spam
self.smtp.sendmail(self.email_from_username, email_to_list, self.email_body.as_string())
Copy the code

After the email is sent, you can log out of the service

def exit(self):
    """Exit service :return:"""
    self.smtp.quit()
Copy the code

Method 2: Zmail

You don’t need to manually add server addresses, ports, and appropriate protocols. You can easily create MIME objects and header files. Note: Zmail only supports Python3, not Python2. First, install the dependency libraries

Install dependency libraries
pip3 install zmail
Copy the code

Then, create a mailbox service object using the mailbox account and authorization code

class ZMailObject(object):
​
    def __init__(self):
        # Email account
        self.username = '**@126.com'

        # Email authorization code
        self.authorization_code = 'Authorization code'

        # Build a mailbox service object
        self.server = zmail.server(self.username, self.authorization_code)
Copy the code

Next, the message subject, message content, and included attachment path are added to a dictionary to form the message body

# Email body
mail_body = {
        'subject': 'Test Report'.'content_text': 'Here's a test report.'.Plain text or HTML content
        'attachments': ['./attachments/report.png'],}Copy the code

Finally, the send_mail() function is called and the message is sent

# the recipient
# can specify a person, a string; It could be multiple people, a list
mail_to = "Recipient 1"

# Send email
self.server.send_mail(mail_to, mail_body)
Copy the code

5. Yagmail

Yagmail requires only a few lines of code to send an email

Compared with Zmail, YagMail provides a more concise and elegant way to send mails

First, install the dependency libraries

Install dependency libraries
pip3 install yagmail
Copy the code

It then connects to the mailbox server through the account, authorization code, and server address and returns a service object

​import yagmail

# Connect to server
User name, authorization code, server address
yag_server = yagmail.SMTP(user='**@126.com', password='Authorization code', host='smtp.126.com')
Copy the code

Next, the mail is sent through the send() function

# Send object list
email_to = ['**@qq.com', ]
email_title = 'Test Report'
email_content = "Here are the details of the test report."
# Attachment list
email_attachments = ['./attachments/report.png',]# Send email
yag_server.send(email_to, email_title, email_content, email_attachments)
Copy the code

After the email is sent, close the connection

# Close connection
yag_server.close()
Copy the code

6. The final

The three ways to send mail in Python are summarized above, and the latter two are more recommended for real projects

I have uploaded all the source code to the public number “AirPython” background, following the public number reply “email” can get all the source code

If you think the article is good, please like, share, leave a message, because this will be my strongest power to continue to output more high-quality articles!

Recommended reading

This black technology, not code can play automation, efficient touch fish

Automated essay | PC this black science and technology to record scripts, the explosive press X elves!

How to combine crawler and automation to help the little sister brush the douyin completely free her hands