Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python SMTP Sending Email

Python SMTP Sending Email

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:

The Python SMTP object uses the sendmail method to send email, with the following syntax:


SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

Parameter Description:

Note the third parameter here: msg is a string representing the email. We know that an email generally consists of a subject, sender, recipient, content, attachments, and so on. When sending an email, pay attention to the format of msg, which is the format defined in the SMTP protocol.

Example

The following example requires that a service supporting SMTP, such as sendmail, is installed on your local machine.

The following is a simple example of sending email using Python:

Example

#!/usr/bin/python

-- coding: UTF-8 --

import

smtplib

from

email

.

mime

.

text

import

MIMEText

from

email

.

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

(

)

)

print

"

Mail sent successfully

"

except

smtplib

.

SMTPException

:

print

"

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.

Execute the above program; if your local machine has sendmail (mail transfer agent)installed, the output will be:


$ python test.py 
邮件发送成功

Check our inbox (usually the spam folder) to see the mail:

If we do not have access to sendmail locally, we can also use SMTP access from other email providers (QQ, NetEase, Google, etc.).

Example

#!/usr/bin/python

-- coding: UTF-8 --

import

smtplib

from

email

.

mime

.

text

import

MIMEText

from

email

.

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

(

)

)

print

"

Mail sent successfully

"

except

smtplib

.

SMTPException

:

print

"

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/python

-- coding: UTF-8 --

import

smtplib

from

email

.

mime

.

text

import

MIMEText

from

email

.

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...

This is a link

"""

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

(

)

)

print

"

Mail sent successfully

"

except

smtplib

.

SMTPException

:

print

"

Error: unable to send mail

"

If you have sendmail installed locally, running the above program outputs:


$ python 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/python

-- coding: UTF-8 --

import

smtplib

from

email

.

mime

.

text

import

MIMEText

from

email

.

mime

.

multipart

import

MIMEMultipart

from

email

.

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

(

)

)

print

"

Mail sent successfully

"

except

smtplib

.

SMTPException

:

print

"

Error: unable to send mail

"


$ python 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/python

-- coding: UTF-8 --

import

smtplib

from

email

.

mime

.

image

import

MIMEImage

from

email

.

mime

.

multipart

import

MIMEMultipart

from

email

.

mime

.

text

import

MIMEText

from

email

.

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...

Runoob Tutorial link

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

(

)

)

print

"

Mail sent successfully

"

except

smtplib

.

SMTPException

:

print

"

Error: unable to send mail

"


$ python 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/python

-- coding: UTF-8 --

import

smtplib

from

email

.

mime

.

text

import

MIMEText

from

email

.

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

mail

(

)

:

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

=

mail

(

)

if

ret

:

print

(

"

Mail sent successfully

"

)

else

:

print

(

"

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/2/library/email-examples.html.