Python uses SMTP to send emails

Source: Internet
Author: User
Python uses SMTP to send Mail SMTP (Simple Mail Transfer Protocol), which is a set of rules for sending Mail from the source address to the destination address, it controls the transfer mode of a letter.

Python's smtplib provides a convenient way to send emails. It encapsulates 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: SMTP server host. You can specify the IP address or domain name of the host, for example, ziqiangxuetang.com. this parameter is optional.

Port: if you provide the host parameter, you must 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 emails. The syntax is as follows:

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

Parameter description:

From_addr: email sender address.

To_addrs: string list, Mail sending address.

Msg: send messages

Note that the third parameter, msg is a string, indicating the mail. We know that an email generally consists of the title, sender, recipient, email content, attachments, etc. when sending an email, pay attention to the msg format. This format is defined in the smtp protocol.

Instance

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

#! /Usr/bin/python

Import smtplib

Sender = 'from @ fromdomain.com'

Receivers = ['to @ todomain.com']

Message = "From: From Person

To: To Person

Subject: SMTP e-mail test

This is a test e-mail message.

"""

Try:

SmtpObj = smtplib. SMTP ('localhost ')

SmtpObj. sendmail (sender, receivers, message)

Print "Successfully sent email"

Failed T SMTPException:

Print "Error: unable to send email"

Use Python to send HTML emails

The difference between sending an HTML-format email in Python and sending a plain text message is to set _ subtype in MIMEText to html. The code is as follows:

Import smtplib

From email. mime. text import MIMEText

Mailto_list = ["YYY@YYY.com"]

Mail_host = "smtp.XXX.com" # set the server

Mail_user = "XXX" # User name

Mail_pass = "XXXX" # Password

Mail_postfix = "XXX.com" # suffix of the sender

Def send_mail (to_list, sub, content): # to_list: recipient; sub: subject; content: Mail content

Me = "hello" + "<" + mail_user + "@" + mail_postfix + ">" # Here, hello can be set at will. after receiving the message, it will be displayed according to the settings.

Msg = MIMEText (content, _ subtype = 'html', _ charset = 'gb2312') # create an instance. here, set it to an html email.

Msg ['subobject'] = sub # set the topic

Msg ['from'] = me

Msg ['to'] = ";". join (to_list)

Try:

S = smtplib. SMTP ()

S. connect (mail_host) # connect to the smtp server

S. login (mail_user, mail_pass) # log on to the server

S. sendmail (me, to_list, msg. as_string () # send an email

S. close ()

Return True

Except t Exception, e:

Print str (e)

Return False

If _ name _ = '_ main __':

If send_mail (mailto_list, "hello", "Xiao Wuyi "):

Print "sent successfully"

Else:

Print "failed to send"

Alternatively, you can specify the Content-type as text/html in the message body, as shown in the following example:

#! /Usr/bin/python

Import smtplib

Message = "From: From Person

To: To Person

MIME-type: 1.0

Content-type: text/html

Subject: smtp html e-mail test

This is an e-mail message to be sent in HTML format

This is HTML message.

This is headline.

"""

Try:

SmtpObj = smtplib. SMTP ('localhost ')

SmtpObj. sendmail (sender, receivers, message)

Print "Successfully sent email"

Failed T SMTPException:

Print "Error: unable to send email"

Python sends emails with attachments

To send an email with an attachment, you must first create a MIMEMultipart () instance, and then construct the attachment. if there are multiple attachments, you can construct them in sequence, and finally use smtplib. smtp to send the email.

From email. mime. text import MIMEText

From email. mime. multipart import MIMEMultipart

Import smtplib

# Create an instance with an attachment

Msg = MIMEMultipart ()

# Construct Attachment 1

Att1 = MIMEText (open ('d: \ 123.rar ', 'RB'). read (), 'base64', 'gb2312 ')

Att1 ["Content-Type"] = 'application/octet-stream'

Att1 ["Content-Disposition"] = 'attachment; filename = "123.doc" '# The filename here can be written as needed, and the name displayed in the email

Msg. attach (att1)

# Construct Attachment 2

Att2 = MIMEText (open ('d: \ 123.txt ', 'RB'). read (), 'base64', 'gb2312 ')

Att2 ["Content-Type"] = 'application/octet-stream'

Att2 ["Content-Disposition"] = 'attachment; filename = "123.txt "'

Msg. attach (att2)

# Add an email header

Msg ['to'] = 'yyy @ YYY.com'

Msg ['from'] = 'XXX @ XXX.com'

Msg ['subobject'] = 'Hello world'

# Send an email

Try:

Server = smtplib. SMTP ()

Server. connect ('smtp .XXX.com ')

Server. login ('XXX', 'xxxxx') # XXX indicates the user name and XXXXX indicates the password.

Server. sendmail (msg ['from'], msg ['to'], msg. as_string ())

Server. quit ()

Print 'sent successfully'

Except t Exception, e:

Print str (e)

The following example specifies that the Content-type header is multipart/mixed and sends the/tmp/test.txt text file:

#! /Usr/bin/python

Import smtplib

Import base64

Filename = "/tmp/test.txt"

# Read the file content and use base64 encoding

Fo = open (filename, "rb ")

Filecontent = fo. read ()

Encodedcontent = base64.b64encode (filecontent) # base64

Sender = 'webmaster @ tutorialpoint.com'

Reciever = 'amrood. admin@gmail.com'

Marker = "AUNIQUEMARKER"

Body = """

This is a test email to send an attachement.

"""

# Define header information

Part1 = "From: From Person

To: To Person

Subject: Sending Attachement

MIME-type: 1.0

Content-Type: multipart/mixed; boundary = % s

-- % S

"% (Marker, marker)

# Define message actions

Part2 = "Content-Type: text/plain

Content-Transfer-Encoding: 8bit

% S

-- % S

"% (Body, marker)

# Defining nearby parts

Part3 = "Content-Type: multipart/mixed; name = \" % s \"

Content-Transfer-Encoding: base64

Content-Disposition: attachment; filename = % s

% S

-- % S --

"% (Filename, filename, encodedcontent, marker)

Message = part1 + part2 + part3

Try:

SmtpObj = smtplib. SMTP ('localhost ')

SmtpObj. sendmail (sender, reciever, message)

Print "Successfully sent email"

Failed T Exception:

Print "Error: unable to send email"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.