Send an email to Python

Time:2022-5-4

Python SMTP send mail

SMTP (Simple Mail Transfer Protocol) is the simple mail transfer protocol. It is a set of rules used to transfer mail from source address to destination address, which controls the transfer mode of mail.

Python’s SMTP lib provides a convenient way to send e-mail. It simply encapsulates the SMTP protocol.

Python creates SMTP objects with the following syntax:

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Parameter Description:

Host: SMTP server host. You can specify the IP address or domain name of the host, such as runoob COM, this is an optional parameter.

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 specify the server address as localhost.

The python SMTP object uses the sendmail method to send mail. The syntax is as follows:

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

Parameter Description:

from_ Addr: mail sender address.

to_ Addrs: string list, email address.

MSG: send message

Notice the third parameter here. MSG is a string, which means mail. We know that e-mail is generally composed of title, sender, recipient, e-mail content, attachments, etc. when sending e-mail, we should pay attention to the format of MSG. This format is defined in the SMTP protocol.

example

The following execution example requires that your local machine has installed a service that supports SMTP, such as sendmail.

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

example

#!/usr/bin/python

– coding: UTF-8 –

import smtplib

from email.mime.text import MIMEText

from email.header import Header

sender = ‘[email protected]

receivers = [‘[email protected]‘] # receive email, which can be set as your QQ email or other email

Three parameters: the first is text content, the second is plain to set text format, and the third is UTF-8 to set code

Message = mimetext (‘python mail sending test… ‘,’ plain ‘,’ UTF-8 ‘)

Message [‘from’] = header (“rookie tutorial”, “UTF-8”) # sender

Message [‘to’] = header (“test”,’utf-8 ‘) # receiver

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 three quotation marks to set the mail information. Standard mail requires three header information: from, to, and subject. Each information is directly separated by blank lines.

We connect to SMTP access by instantiating the SMTP object smtpobj of the smtplib module, and use the sendmail method to send information.

Execute the above procedure. If you install sendmail (mail transfer agent) locally, it will output:

$ python test.py

Mail sent successfully

Check our inbox (usually in the trash can) and you can view the email information:

If we don’t have sendmail access, we can also use the SMTP access of other mail service 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 service

mail_ host=”smtp. XXX. Com “# setup server

mail_ User = “XXXX” # user name

mail_ Pass = “XXXXXX” # password

sender = ‘[email protected]

receivers = [‘[email protected]‘] # receive email, which can be set as your QQ email or other email

Message = mimetext (‘python mail sending test… ‘,’ plain ‘,’ UTF-8 ‘)

Message [‘from’] = header (“rookie tutorial”, “UTF-8”)

Message [‘to’] = header (“test”, “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 mail in HTML format using Python

Python sends mail in HTML format, which is different from sending mail in plain text message, that is, it puts mime text into_ The subtype is set to HTML. The specific codes are as follows:

example

#!/usr/bin/python

– coding: UTF-8 –

import smtplib

from email.mime.text import MIMEText

from email.header import Header

sender = ‘[email protected]

receivers = [‘[email protected]‘] # receive email, which can be set as your QQ email or other email

mail_msg = “””

Python mail sending test

This is a link

“””

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”

Execute the above procedure. If you install sendmail locally, you will output:

$ python test.py

Mail sent successfully

Check our inbox (usually in the trash can) and you can view the email information:

Python sends mail with attachments

To send an email with attachments, first create an instance of mimemultipart (), then construct the attachments. If there are multiple attachments, construct them in turn, and finally use SMTP lib SMTP send.

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 = ‘[email protected]

receivers = [‘[email protected]‘] # receive email, which can be set as your QQ email or other email

#Create an instance with attachments

message = MIMEMultipart()

Message [‘from’] = header (“rookie tutorial”, “UTF-8”)

Message [‘to’] = header (“test”, “UTF-8”)

Subject = ‘Python SMTP mail test’

message[‘Subject’] = Header(subject, ‘utf-8’)

#Message body content

message. Attach (mimetext (‘This is a rookie tutorial Python mail sending test… ‘,’ plain ‘,’ UTF-8 ‘))

Construct attachment 1 and transfer the test in the current directory Txt file

att1 = MIMEText(open(‘test.txt’, ‘rb’).read(), ‘base64’, ‘utf-8’)

att1[“Content-Type”] = ‘application/octet-stream’

The filename here can be written arbitrarily. What name is written and what name is displayed in the email

att1[“Content-Disposition”] = ‘attachment; filename=”test.txt”‘

message.attach(att1)

Construct attachment 2 and transfer the runoob in the current directory Txt file

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

Mail sent successfully

Check our inbox (usually in the trash can) and you can view the email information:

Add pictures to HTML text

In the HTML text of e-mail, it is invalid for general e-mail service providers to add external chains. The example of correctly adding pictures is as follows:

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 = ‘[email protected]

receivers = [‘[email protected]‘] # receive email, which can be set as your QQ email or other email

msgRoot = MIMEMultipart(‘related’)

Msgroot [‘from’] = header (“rookie tutorial”, “UTF-8”)

Msgroot [‘to’] = header (“test”, “UTF-8”)

Subject = ‘Python SMTP mail test’

msgRoot[‘Subject’] = Header(subject, ‘utf-8’)

msgAlternative = MIMEMultipart(‘alternative’)

msgRoot.attach(msgAlternative)

mail_msg = “””

Python mail sending test

Define the picture ID and reference it in 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

Mail sent successfully

Check our inbox (if you need to move to the inbox to display normally in the trash can), you can view the mail information:

Send using a third-party SMTP service

The SMTP service of QQ mailbox (you can also use 163, Gmail, etc.) is used here. The following configuration is required:

QQ mailbox sets the password by generating the authorization code:

QQ mailbox SMTP server address: SMTP qq. COM, SSL port: 465.

You need to modify the following examples: sender email (your QQ email), password, recipient email (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=‘[email protected]‘# sender email account

my_ Pass = ‘xxxxxxxxx’ # sender email password

my_user=‘[email protected]‘# recipient’s email account, I’ll send it to myself

def mail():

ret=True

try:

MSG = mimetext (‘fill in email content ‘,’ plain ‘,’ UTF-8 ‘)

MSG [‘from’] = formataddr ([“fromrunoob”, my_sender]) # the corresponding sender email nickname and sender email account in brackets

MSG [‘to’] = formataddr ([“FK”, my_user]) # the corresponding recipient email nickname and recipient email account in brackets

MSG [‘subject’] = “rookie tutorial sending email test” # the subject of the email can also be said to be the title

server=smtplib. SMTP_ SSL ("SMTP. QQ. Com", 465) # SMTP server in sender's mailbox, port 25

ret=mail()

if ret:

Print (“mail sent successfully”)

else:

Print (“mail sending failed”)

$ python test.py

Mail sent successfully

After sending successfully, log in to the recipient’s email to view:

For more information, see:https://docs.python.org/2/library/email-examples.html。

This work adoptsCC agreement, reprint must indicate the author and the link to this article