Python3 Send Email via SMTP
SMTP (Simple Mail Transfer Protocol) is a set of rules for transferring mail from a source address to a destination address, which controls how messages are relayed.
Python's smtplib provides a convenient way to send email. It is a simple wrapper around the SMTP protocol.
The syntax for creating an SMTP object in Python is as follows:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Parameter Description:
- host: the SMTP server host. You can specify the host's IP address or domain name such as runoob.com; this parameter is optional.
- port: if you provide the host parameter, you need to specify the port number used by the SMTP service; generally the SMTP port number is 25.
- local_hostname: if SMTP is on your local machine, you only need to set the server address to localhost.
A Python SMTP object sends mail with the sendmail method, whose syntax is as follows:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
Parameter Description:
- from_addr: the sender's email address.
- to_addrs: a list of strings, the recipient addresses.
- msg: the message to send
Note the third parameter: msg is a string representing the mail. We know that mail generally consists of a subject, sender, recipients, body, attachments and so on, so when sending mail you need to pay attention to the format of msg. This format is the one defined in the SMTP protocol.
Example
The following is a simple example of sending mail with Python:
Example
#!/usr/bin/python3
import
smtplib
from
.
mime
.
text
import
MIMEText
from
.
header
import
Header
sender
=
'
from@runoob.com
'
receivers
=
[
'
429240967@qq.com
'
]
The receiving address; you can set it to your QQ mailbox or another mailbox
Three parameters: the first is the text content, the second plain sets the text format, and the third utf-8 sets the encoding
message
=
MIMEText
(
'
Python email sending test...
'
,
'
plain
'
,
'
utf-8
'
)
message
[
'
From
'
]
=
Header
(
"
Runoob Tutorial
"
,
'
utf-8
'
)
Sender
message
[
'
To
'
]
=
Header
(
"
Testing
"
,
'
utf-8
'
)
Recipient
subject
=
'
Python SMTP mail test
'
message
[
'
Subject
'
]
=
Header
(
subject
,
'
utf-8
'
)
try
:
smtpObj
=
smtplib
.
SMTP
(
'
localhost
'
)
smtpObj
.
sendmail
(
sender
,
receivers
,
message
.
as_string
(
)
)
(
"
Mail sent successfully
"
)
except
smtplib
.
SMTPException
:
(
"
Error: unable to send mail
"
)
We use triple quotes to set the mail message; a standard mail needs three header fields: From, To, and LinkedHashMap, among others. Subject , with each field separated directly by a blank line.
We instantiate the SMTP object of the smtplib module smtpObj to connect to the SMTP service, and use the sendmail method to send the message.
If you have sendmail installed locally, running the above program outputs:
$ python3 test.py
邮件发送成功
Check our inbox (usually the spam folder) to see the mail:

If we do not have sendmail access locally, we can also use the SMTP service of other providers (QQ, NetEase, Google, etc.).
Example
#!/usr/bin/python3
import
smtplib
from
.
mime
.
text
import
MIMEText
from
.
header
import
Header
Third-party SMTP services
mail_host
=
"
smtp.XXX.com
"
# Set the server
mail_user
=
"
XXXX
"
# User name
mail_pass
=
"
XXXXXX
"
# Password
sender
=
'
from@runoob.com
'
receivers
=
[
'
429240967@qq.com
'
]
The receiving address; you can set it to your QQ mailbox or another mailbox
message
=
MIMEText
(
'
Python email sending test...
'
,
'
plain
'
,
'
utf-8
'
)
message
[
'
From
'
]
=
Header
(
"
Runoob Tutorial
"
,
'
utf-8
'
)
message
[
'
To
'
]
=
Header
(
"
Testing
"
,
'
utf-8
'
)
subject
=
'
Python SMTP mail test
'
message
[
'
Subject
'
]
=
Header
(
subject
,
'
utf-8
'
)
try
:
smtpObj
=
smtplib
.
SMTP
(
)
smtpObj
.
connect
(
mail_host
,
25
)
25 is the SMTP port number
smtpObj
.
login
(
mail_user
,
mail_pass
)
smtpObj
.
sendmail
(
sender
,
receivers
,
message
.
as_string
(
)
)
(
"
Mail sent successfully
"
)
except
smtplib
.
SMTPException
:
(
"
Error: unable to send mail
"
)
Send HTML-formatted mail with Python
The difference between sending HTML mail and plain text mail with Python is that the _subtype in MIMEText is set to html. The code is as follows:
Example
#!/usr/bin/python3
import
smtplib
from
.
mime
.
text
import
MIMEText
from
.
header
import
Header
sender
=
'
from@runoob.com
'
receivers
=
[
'
429240967@qq.com
'
]
The receiving address; you can set it to your QQ mailbox or another mailbox
mail_msg
=
"""
Python email sending test...
"""
message
=
MIMEText
(
mail_msg
,
'
html
'
,
'
utf-8
'
)
message
[
'
From
'
]
=
Header
(
"
Runoob Tutorial
"
,
'
utf-8
'
)
message
[
'
To
'
]
=
Header
(
"
Testing
"
,
'
utf-8
'
)
subject
=
'
Python SMTP mail test
'
message
[
'
Subject
'
]
=
Header
(
subject
,
'
utf-8
'
)
try
:
smtpObj
=
smtplib
.
SMTP
(
'
localhost
'
)
smtpObj
.
sendmail
(
sender
,
receivers
,
message
.
as_string
(
)
)
(
"
Mail sent successfully
"
)
except
smtplib
.
SMTPException
:
(
"
Error: unable to send mail
"
)
If you have sendmail installed locally, running the above program outputs:
$ python3 test.py
邮件发送成功
Check our inbox (usually the spam folder) to see the mail:

Python Send Mail with Attachments
To send mail with attachments, first create a MIMEMultipart() instance, then construct the attachments (several can be constructed in turn), and finally send with smtplib.smtp.
Example
#!/usr/bin/python3
import
smtplib
from
.
mime
.
text
import
MIMEText
from
.
mime
.
multipart
import
MIMEMultipart
from
.
header
import
Header
sender
=
'
from@runoob.com
'
receivers
=
[
'
429240967@qq.com
'
]
The receiving address; you can set it to your QQ mailbox or another mailbox
# Create an instance with attachments
message
=
MIMEMultipart
(
)
message
[
'
From
'
]
=
Header
(
"
Runoob Tutorial
"
,
'
utf-8
'
)
message
[
'
To
'
]
=
Header
(
"
Testing
"
,
'
utf-8
'
)
subject
=
'
Python SMTP mail test
'
message
[
'
Subject
'
]
=
Header
(
subject
,
'
utf-8
'
)
# Mail body content
message
.
attach
(
MIMEText
(
'
This is a Runoob Tutorial Python email sending test...
'
,
'
plain
'
,
'
utf-8
'
)
)
Construct attachment 1, sending the test.txt file in the current directory
att1
=
MIMEText
(
open
(
'
test.txt
'
,
'
rb
'
)
.
read
(
)
,
'
base64
'
,
'
utf-8
'
)
att1
[
"
Content-Type
"
]
=
'
application/octet-stream
'
The filename here can be anything; whatever name you write is the name shown in the mail
att1
[
"
Content-Disposition
"
]
=
'
attachment; filename="test.txt"
'
message
.
attach
(
att1
)
Construct attachment 2, sending the runoob.txt file in the current directory
att2
=
MIMEText
(
open
(
'
runoob.txt
'
,
'
rb
'
)
.
read
(
)
,
'
base64
'
,
'
utf-8
'
)
att2
[
"
Content-Type
"
]
=
'
application/octet-stream
'
att2
[
"
Content-Disposition
"
]
=
'
attachment; filename="runoob.txt"
'
message
.
attach
(
att2
)
try
:
smtpObj
=
smtplib
.
SMTP
(
'
localhost
'
)
smtpObj
.
sendmail
(
sender
,
receivers
,
message
.
as_string
(
)
)
(
"
Mail sent successfully
"
)
except
smtplib
.
SMTPException
:
(
"
Error: unable to send mail
"
)
$ python3 test.py
邮件发送成功
Check our inbox (usually the spam folder) to see the mail:

Add images in the HTML text
External links added to the HTML text of a mail are generally ineffective with most mail providers; the correct way to add an image is shown below:
Example
#!/usr/bin/python3
import
smtplib
from
.
mime
.
image
import
MIMEImage
from
.
mime
.
multipart
import
MIMEMultipart
from
.
mime
.
text
import
MIMEText
from
.
header
import
Header
sender
=
'
from@runoob.com
'
receivers
=
[
'
429240967@qq.com
'
]
The receiving address; you can set it to your QQ mailbox or another mailbox
msgRoot
=
MIMEMultipart
(
'
related
'
)
msgRoot
[
'
From
'
]
=
Header
(
"
Runoob Tutorial
"
,
'
utf-8
'
)
msgRoot
[
'
To
'
]
=
Header
(
"
Testing
"
,
'
utf-8
'
)
subject
=
'
Python SMTP mail test
'
msgRoot
[
'
Subject
'
]
=
Header
(
subject
,
'
utf-8
'
)
msgAlternative
=
MIMEMultipart
(
'
alternative
'
)
msgRoot
.
attach
(
msgAlternative
)
mail_msg
=
"""
Python email sending test...
Image demonstration:
"""
msgAlternative
.
attach
(
MIMEText
(
mail_msg
,
'
html
'
,
'
utf-8
'
)
)
Set the image to the current directory
fp
=
open
(
'
test.png
'
,
'
rb
'
)
msgImage
=
MIMEImage
(
fp
.
read
(
)
)
fp
.
close
(
)
Define the image ID and reference it in the HTML text
msgImage
.
add_header
(
'
Content-ID
'
,
'
'
)
msgRoot
.
attach
(
msgImage
)
try
:
smtpObj
=
smtplib
.
SMTP
(
'
localhost
'
)
smtpObj
.
sendmail
(
sender
,
receivers
,
msgRoot
.
as_string
(
)
)
(
"
Mail sent successfully
"
)
except
smtplib
.
SMTPException
:
(
"
Error: unable to send mail
"
)
$ python3 test.py
邮件发送成功
Check our inbox (if it is in the spam folder, you may need to move it to the inbox for it to display properly) to see the email information:

Send using a third-party SMTP service
Here we use the SMTP service of QQ Mail (you can also use 163, Gmail, etc.), which requires the following configuration:

QQ mailbox sets the password by generating an authorization code:

QQ Mail SMTP server address: smtp.qq.com, SSL port: 465.
In the following example you need to modify: the sender's email address (your QQ email), the password, and the recipient's email address (you can send it to yourself).
QQ SMTP
#!/usr/bin/python3
import
smtplib
from
.
mime
.
text
import
MIMEText
from
.
utils
import
formataddr
my_sender
=
'
429240967@qq.com
'
Sender email account
my_pass
=
'
xxxxxxxxxx
'
Sender email password
my_user
=
'
429240967@qq.com
'
Recipient email account; here I send it to myself
def
(
)
:
ret
=
True
try
:
msg
=
MIMEText
(
'
Fill in the email content
'
,
'
plain
'
,
'
utf-8
'
)
msg
[
'
From
'
]
=
formataddr
(
[
"
FromRunoob
"
,
my_sender
]
)
The values in parentheses correspond to the sender's nickname and the sender's email account
msg
[
'
To
'
]
=
formataddr
(
[
"
FK
"
,
my_user
]
)
The values in parentheses correspond to the recipient's nickname and the recipient's email account
msg
[
'
Subject
'
]
=
"
Runoob Tutorial email sending test
"
The subject of the email, in other words the title
server
=
smtplib
.
SMTP_SSL
(
"
smtp.qq.com
"
,
465
)
The SMTP server of the sender's mailbox; the port is 25
server
.
login
(
my_sender
,
my_pass
)
The values in parentheses correspond to the sender's email account and the email password
server
.
sendmail
(
my_sender
,
[
my_user
,
]
,
msg
.
as_string
(
)
)
The values in parentheses correspond to the sender's email account, the recipient's email account, and the send-mail call
server
.
quit
(
)
Close the Connection
except
Exception
:
If the statements in try are not executed, the following ret=False will be executed
ret
=
False
return
ret
ret
=
(
)
if
ret
:
(
"
Mail sent successfully
"
)
else
:
(
"
Failed to send the email
"
)
$ python test.py
邮件发送成功
After sending successfully, log in to the recipient's mailbox to view it:

For more content, please refer to:https://docs.python.org/3/library/email-examples.html。