SoFunction
Updated on 2025-03-02

Basic analysis of sending emails in Python

1. Introduction to python mail module

The email module is a built-in module, which uses Chinese, topic, date, attachment and other information to customize the email;

The smtplib module is a built-in module. It simply encapsulates the smtp protocol and can realize mail sending.

2. Email sending steps

Create an SMTP operation object and connect to the SMTP target server, which can be 163, QQ, etc.

Use your own account to log in to the target server (your email address and email authorization code)

Call the method in the object and send an email to the destination address

The sample code is as follows:

import smtplib

server = () 
(smtp_server) # The SMTP server in the sender's mailbox, the default port is 25(sender, passwd) # Sender's email account, email authorization code# msg.as_string() in msg.as_string() turns msg (MIMEText or MIMEMultipart object) into str.(sender, receive, msg.as_string()) 
()

The above code does not fill in the actual value and cannot be executed directly. There are the following points to note:

msg is our email information object, defined through the email module

Email Authorization Code Password for non-login email, readers need to enter QQ mailbox or other emailbox to open and obtain according to the steps

The practical code for simple email is as follows:

import smtplib
from  import MIMEText
smtp = ()
('')
('329999897@','***Authorization Code***')

msg = MIMEText('This is a test email', "html", "utf-8") #Email information objectmsg['from'] = '329999897@' # Send the email addressmsg['to'] = ‘liusir@' # Email recipient's email addressmsg['subject'] = ‘Test mail' #Email Subject
('329999897@','liusir@',msg.as_string())
()

You can complete the simple email sending at this time.

You can also bring attachments when sending emails, and share them next time.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.