Use the smtplib and email modules in python to send mail instances

Source: Internet
Author: User
Tags smtp sendmail starttls

SMTP Module

Among so many defined classes, we usually use the smtplib. SMTP class. Let's take a look at the usage of this class:
An smtp instance encapsulates an smtp connection, which supports all SMTP and ESMTP operation commands. If the host and port parameters are defined, smtp will automatically call the connect () method during initialization, if the connect () method fails, the SMTPConnectError exception is triggered. The timeout parameter sets the timeout time. In the general call process, follow the connetc (), sendmail (), and quit () steps.

SMTP module Methods

Let's take a look at the methods of this class:
Copy codeThe Code is as follows:
SMTP. set_debuglevel (level)
Sets the output debug debugging information. debugging information is not output by default.
SMTP.doc md (cmd [, argstring])
Send a command to the smtp server,
SMTP. connect ([host [, port])
Connect to the specified smtp server. The default port is port 25 of the local machine. It can also be written as hostname: port.
SMTP. helo ([hostname])
Use the helo command to confirm your identity with the smtp server.
SMTP. ehlo ([hostname])
Use the ehlo command to confirm your identity with the esmtp server.
SMTP. ehlo_or_helo_if_needed ()
If the ehlo or helo commands are not provided in the previous session connection, this method calls ehlo () or helo ().
SMTP. has_extn (name)
Determines whether the specified name is on the smtp server.
SMTP. verify (address)
Determines whether the email address exists on the smtp server.
SMTP. login (user, password)
Log on to the smtp server to be verified. If the ehlo or helo commands are not provided before, the ehlo command of ESMTP is first attempted.
SMTP. starttls ([keyfile [, certfile])
Make the smtp connection run in TLS mode, and all smtp commands will be encrypted.
SMTP. sendmail (from_addr, to_addrs, msg [, mail_options, rcpt_options])
Send an email. This method requires some email addresses and messages.
SMTP. quit ()
Terminate the smtp session and close the connection.

After searching and learning, we found that most of the online emails are sent using the smtp sendmail method. Let's take a look at this example:

Use sendmail to send emails
Copy codeThe Code is as follows:
Import smtplib
Import time
From email. message import Message
From time import sleep
Import email. utils
Import base64

Smtpserver = 'smtp .gmail.com'
Username = 'username @ gmail.com'
Password = 'Password'

From_addr = 'from @ gmail.com'
To_addr = 'tooooooo @ qq.com'
Cc_addr = 'ccccccccc @ qq.com'

Time = email. utils. formatdate (time. time (), True)

Message = Message ()
Message ['subobject'] = 'mail subobject'
Message ['from'] = from_addr
Message ['to'] = to_addr
Message ['cc'] = cc_addr
Message. set_payload ('mail content' + time)
Msg = message. as_string ()

Sm = smtplib. SMTP (smtpserver, port = 587, timeout = 20)
Sm. set_debuglevel (1)
Sm. ehlo ()
Sm. starttls ()
Sm. ehlo ()
Sm. login (username, password)

Sm. sendmail (from_addr, to_addr, msg)
Sleep (5)
Sm. quit ()

Email Module

If you want to include attachments, use html to write emails, and attach images to emails, you need to use the email module and Its submodules. Let's take a look at the email package. The email package is used to manage email information, including MIME and other message formats based on RFC 2822. The main feature of an email package is that it parses and generates email information separately.

A mime Message consists of a message header and a message body, which are the mail header and body. The header and body are separated by blank lines.

The mail header contains important information such as the sender, recipient, subject, time, MIME Version, and mail content type. Each piece of information is called a domain, which is composed of ":" and information content after the domain name. It can be a row, long or occupying multiple rows. The first line of the domain must be written with a "Header", that is, there must be no blank characters (spaces and tabs) on the left side. To continue a line, you must start with a blank character, the first blank character is not inherent in the information.

The body contains the Content of the email. Its Type is indicated by the Content-Type field in the email header. The most common types are text/plain (plain text) and text/html (hypertext ). The body is divided into multiple segments, each of which contains two parts: the header and the body. These two parts are also separated by blank lines. There are three common multipart types: multipart/mixed, multipart/related, and multipart/alternative.
The email package contains many modules:
Copy codeThe Code is as follows:
Email. message
Email. parser
Email. generator
Create email and mime objects using email. MIME
Email. header
Email. charset
Email. encoders
Email. ereors
Email. utils
Email. iterators

Let's take a look at email. mime. This module is mainly used when attachments, images, and audio are carried in the email. Generally, you parse a file or text to generate a message object structure. You can also create a message structure from the beginning. In fact, you can append a new message object to an existing message structure. You can create an object structure by creating a message instance, and then append the attachment and header information to the structure. The email package provides subclass to make this operation easy.
Simulate carrying an image in the email content, as shown below:

The email contains images.
Copy codeThe Code is as follows:
From email. mime. text import MIMEText
From email. mime. multipart import MIMEMultipart
From email. mime. image import MIMEImage
Import smtplib

From_mail = 'froooooooom @ gmail.com'
To_mail = 'toooooooooo @ qq.com'

Msg = MIMEMultipart ()
Msg ['from'] = from_mail
Msg ['to'] = to_mail
Msg ['subobject'] = 'python mail Test'

Body = 'test img send'
Con = MIMEText ('<B> % s </B>

'% Body, 'html ')
Msg. attach (con)

Img = MIMEImage (file ('d: \ 10535-102.jpg ', 'rb'). read ())
Img. add_header ('content-id', 'd: \ 10535-102.jpg ')
Msg. attach (img)

Server = smtplib. SMTP ('smtp .gmail.com ')
Server.doc md ('ehol', 'tooooooo @ gmail.com ')
Server. starttls ()
Server. login ('username @ gmail.com ', 'Password ')

Server. sendmail (from_mail, to_mail, msg. as_string ())
Server. quit ()

Attachments in the email

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. Finally, use smtplib. smtp to send the email.
Simulate attaching an attachment to an email as follows:
Copy codeThe Code is as follows:
From email. mime. text import MIMEText
From email. mime. multipart import MIMEMultipart
Import smtplib

# Create an instance with an attachment
Msg = MIMEMultipart ()

Txt = MIMEText ("this is the content of a Chinese email", 'plain ', 'gb2312 ')
Msg. attach (txt)
# Construct Attachment 1
Att1 = MIMEText (open ('d: \ drcom.rar ', 'rb'). read (), 'base64', 'gb2312 ')
Att1 ["Content-Type"] = 'application/octet-stream'
Att1 ["Content-Disposition"] = 'attachment; filename = "drcom.rar" '# Here, the filename 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'] = 'tooooooo @ qq.com'
Msg ['from'] = 'frommmmmmm @ gmail.com'
Msg ['subobject'] = 'Hello world'

 

 
# Send an email
Try:
Server = smtplib. SMTP ()
Server. connect ('smtp .gmail.com ')
Server. starttls ()
Server. login ('xxxxx @ gmail.com ', 'xxxxxxxxxxxx') # 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)

Related Article

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.