[Python actual combat application] Python send Gmail email actual combat teaching

Insert picture description here

In most of today's websites, whether it is successful registration, resetting a password, preferential news or new products on the shelves, etc., customers will be notified via email, which is an indispensable way of delivering messages on the website. In addition, some developers will notify the crawled information via email when they run the crawler. From the above situation, we can know that e-mail is frequently used and its importance to website functions. Therefore, this article will use the Visual Studio Code development tool to introduce how to send e-mails through Python and customize the e-mail template. contain:

Basic email content

Get the Gmail application password

Set up SMTP server (SMTP Server)

Add pictures to email content

Customized email templates (Templates)

1. Basic email content

First, refer to the MIMEMultipart category in the Python email standard library (Standard Library), as shown in the following example:

from email.mime.multipart import MIMEMultipart

The mime (Multipurpose Internet Mail Extensions) sub-package under the email package (Package) is the Internet media type, which defines the format standard for transmitting e-mail on the Internet. In the multipart sub-package under it, the MIMEMultipart category enables electronic The format of the email contains plain text or HTML content. And a basic email has title, sender, recipient, and content. You can set the data of each field through the MIMEMultipart object, as shown in the following example:

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText



content = MIMEMultipart()  #建立MIMEMultipart物件

content["subject"] = "Learn Code With Mike"  #邮件标题

content["from"] = "[email protected]"  #寄件者

content["to"] = "[email protected]" #收件者

content.attach(MIMEText("Demo python send email"))  #邮件內容

In the example, the mail content is set using the attach method (Method) of the MIMEMultipart object, and the content needs to refer to the MIMEText category to create the object. The first parameter is passed in the text content, and the second parameter can specify plain text or HTML. The default is For plain text. The HTML content of the email will be explained when we customize the email template in Section 5 of this article.

2. Obtaining the password of the Gmail application
In the Python project, if you want to send emails through Gmail's SMTP server, you need to obtain the exclusive password of the application, because Google considers Python's smtplib library to be high-risk, so It is not possible to send emails through the application with the original Gmail password. The following are the steps to obtain the application password:

Step 1: Enter the sender’s Google account.

Please click to enter the picture description (up to 18 characters)

Step 2: Click the security tab in the left column, and then set up two-step verification.

Please click to enter the picture description (up to 18 characters)

Step 3: After the two-step setting is completed, you will see an additional application password below.

Please click to enter the picture description (up to 18 characters)

Step 4: Select Others in the place where you select the application.

Please click to enter the picture description (up to 18 characters)

Step 5: Then enter the name of the application and click Generate.

Please click to enter the picture description (up to 18 characters)

Step 6: Finally, you can get the password of the application.

Please click to enter the picture description (up to 18 characters)

3. Set up the SMTP server (SMTP Server)
After the email content in the Python project is completed, the next step is to set up Gmail's SMTP to send it completely. The setting method is as follows:

import smtplib
with smtplib.SMTP(host="smtp.gmail.com", port="587") as smtp:  # 設定SMTP伺服器
    try:
        smtp.ehlo()  # 驗證SMTP伺服器
        smtp.starttls()  # 建立加密傳輸
        smtp.login("[email protected]", "應用程式密碼")  # 登入寄件者gmail
        smtp.send_message(content)  # 寄送郵件
        print("Complete!")
    except Exception as e:
        print("Error message: ", e)

Refer to the smtplib module (Module), and then specify the server location and port number through the keyword argument (Keyword Argument) according to the SMTP used. In addition, the with statement of Python is used here to automatically release resources when the mail is sent. After creating the SMTP object, use the ehlo() method to verify whether the SMTP server and port number are correct. The next step is to call the starttls() method to establish TLS (Transport Layer Security) transmission, which is a network transmission security protocol to protect data Security and integrity. Finally, log in to the sender’s Gmail account and send the mail. It is recommended to use the Python exception handling mechanism, because in the process of sending emails, there is a great chance that exception errors will occur. Log in to the recipient’s Gmail, and you can see the email just sent, as shown in the following example:

Please click to enter the picture description (up to 18 characters)

4. Adding images
to email content If you want to add images to emails, you need to quote the MIMEImage category in the Python project, and reference the pathlib library to read the images, as shown in the following example:

from email.mime.image import MIMEImage
from pathlib import Path

Add a picture to the project. This article uses koala.jpg as a demonstration. Then, in the place where the mail content is set, a MIMEImage object is created, and the binary code of the picture is passed in. The read_bytes() of the Path object can be used. Method to read, the following example:

content = MIMEMultipart()  # 建立MIMEMultipart物件
content["subject"] = "Learn Code With Mike"  # 郵件標題
content["from"] = "[email protected]"  # 寄件者
content["to"] = "[email protected]"  # 收件者
content.attach(MIMEText("Demo python send email"))  # 郵件純文字內容
content.attach(MIMEImage(Path("koala.jpg").read_bytes()))  # 郵件圖片內容

After the delivery is complete, log in to the recipient’s Gmail, and you can see that the email content has successfully added a picture, as shown in the following example:

Please click to enter the picture description (up to 18 characters)

5. Customized email templates (Templates) In
practice, in addition to pure text emails, there are usually opportunities to customize the format of the email content according to the situation. For example, some texts need to be colored, bold, and hyperlinks. Wait, at this time, you can use HTML to customize email templates according to different needs. In the Python project, add a file named success_template.html, assuming that when the user is successfully registered, you want to use this email template for notification. Before starting to design the sample mail version, here is a little trick to teach you. After opening the success_template.html file, you can see the language mode in the lower right corner of Visual Studio Code, as shown in the following example:

Please click to enter the picture description (up to 18 characters)

If it is already HTML, there is no need to change it. If other languages ​​are displayed, click the red box, enter HTML in the search place, and select. Next, enter the! Symbol in the first line of the success_template.html file, press the Tab key, and the basic HTML code will be automatically generated, as shown in the following example:

Please click to enter the picture description (up to 18 characters)

Since the email template does not require the content in the label, you can delete it, and then enter the formatted content of the email in the label area, as shown in the following example:

Please click to enter the picture description (up to 18 characters)

In this email sample, a user variable is set, with a $ symbol in front of it, to indicate that this parameter is dynamically passed in by the Python code, and the bold font is displayed. The Google string below has added hyperlinks. Back to the main Python program, reference the Template category of the string module (Module) to replace the parameter values ​​in the email template. The following example:

from string import Template

Next, create a Template object and pass in the email template content, which can be achieved through the read_text() method of the Path object. Finally, call the substitute() method of the Template object to set the parameter values ​​in the email template. The parameters can be passed into the Python dictionary (Dictionary) or keyword arguments (Keyword Argument), as shown in the following example:

template = Template(Path("success_template.html").read_text())
body = template.substitute({
    
     "user": "Mike" })

Pass the body in the specified mail content of the MIMEMultipart object and set it to the HTML format, as shown in line 10 of the following example:

content = MIMEMultipart()  # 建立MIMEMultipart物件
content["subject"] = "Learn Code With Mike"  # 郵件標題
content["from"] = "[email protected]"  # 寄件者
content["to"] = "[email protected]"  # 收件者
template = Template(Path("success_template.html").read_text())
body = template.substitute({
    
     "user": "Mike" })
content.attach(MIMEText(body, "html"))  # HTML郵件內容

Log in to the recipient’s Gmail, and you can see the results of the customized email template, as shown in the following example:

Please click to enter the picture description (up to 18 characters)

6. Summary
I hope that after reading this article, I can understand how to send emails through Python, and have the ability to customize the required email templates, which can then be applied to their respective projects. If you encounter any problems during the exercise, please leave a message to share.

Guess you like

Origin blog.csdn.net/wlcs_6305/article/details/114632202