Use Smtplib and email modules in Python to send message instances _python

Source: Internet
Author: User
Tags base64 rar sleep starttls in python

SMTP module

Of the many defined classes, our most common is smtplib. SMTP class, take a specific look at the usage of the class:
The SMTP instance encapsulates an SMTP connection that supports all SMTP and ESMTP operation instructions, and if the host and port parameters are defined, SMTP automatically invokes the Connect () method during initialization, and if the Connect () method fails, The smtpconnecterror exception is triggered, and the timeout parameter sets the timeout time. You should follow the Connetc (), SendMail (), quit () steps in the general invocation process.

Main method of SMTP module

Let's take a look at the method of this class:

Copy Code code as follows:

Smtp.set_debuglevel (Level)
Sets output debug debug information and does not output debug information by default.
Smtp.docmd (cmd[, argstring])
Send a command to the SMTP server,
Smtp.connect ([host[, Port]])
Connects to the specified SMTP server, which defaults to port 25 on this computer. It can also be written in hostname:port form.
Smtp.helo ([hostname])
Use the HELO directive to confirm your identity to the SMTP server.
Smtp.ehlo ([hostname])
Use the EHLO command to confirm your identity to the ESMTP server.
Smtp.ehlo_or_helo_if_needed ()
This method calls EHLO () or helo () if no EHLO or helo instructions are provided in the previous session connection.
Smtp.has_extn (name)
Determines whether the specified name is on the SMTP server.
Smtp.verify (Address)
Determine if the mail address exists on the SMTP server.
Smtp.login (user, password)
Log in to the SMTP server that needs to be authenticated, and if no EHLO or helo instructions have been provided before, the ESMTP EHLO instructions will be attempted first.
Smtp.starttls ([keyfile[, CertFile]])
Causes the SMTP connection to run in TLS mode, and all SMTP directives are encrypted.
Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, Rcpt_options])
To send a message, this method requires some e-mail addresses and messages.
Smtp.quit ()
Terminates the SMTP session and closes the connection.

After search learning found that most of the Internet is using the SMTP class SendMail this method to send mail, let's take a look at this example:

Send mail using SendMail

Copy Code code 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[' Subject ' = ' Mail Subject '
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 carry an attachment in a message, use HTML to write a message, attach a picture, and so on, you need to use the email module and its child modules. Here's a look at email packets, which are used to manage email messages, including MIME and other RFC 2822-based message formats. The main feature of an email packet is that it is a separate module to parse and generate the email information inside it.

A MIME message consists of a message header and a message body, in which the message header and the message body are part of the message. The message header is separated from the message body by a blank line.

Message headers contain important information such as the sender, recipient, subject, Time, MIME version, type of message content, and so on. Each piece of information is called a domain, followed by the domain name ":" and the content of the information composition, can be a row, longer can occupy more than one line. The first line of the field must be written "head", which means that the left side cannot have white space characters (spaces and tabs); the continuation line must begin with a blank character, and the first whitespace character is not intrinsic to the information itself.

The message body contains the contents of the message, and its type is indicated by the "Content-type" field of the message header. The most common types are text/plain (plain text) and text/html (hypertext). The body of the message is divided into segments, each with a segment header and a section body, separated by a blank line between the two parts. There are three common types of multipart: multipart/mixed, multipart/related and multipart/alternative.
In the email package contains a number of modules:

Copy Code code as follows:

Email.message
Email.parser
Email.generator
Email.mime Create email and MIME objects
Email.header
Email.charset
Email.encoders
Email.ereors
Email.utils
Email.iterators

Mainly to see Email.mime, in the mail to carry accessories, pictures, audio, the main use of the module. Typically, you create a Message object structure by parsing a file or a piece of text, or you can build a message structure from scratch, in fact, you can append a new message object to an existing message structure. You can create an object structure by creating an instance of the message, and then append the attachment and header information to the structure. The email package provides subclasses that make the operation easy.
Simulate carrying pictures in the content of the message as follows:

Carry pictures in the content of the message

Copy Code code 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.co M '
To_mail = ' toooooooooo@qq.com '

msg = Mimemultipart ()
msg[' from '] = From_mail
msg[' to '] = To_m Ail
msg[' Subject '] = ' python mail test '

BODY = ' test img send '
con = mimetext (' <b>%s</b>

"% body, ' html ')
Msg.attach (con)

img = mimeimag E (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.docmd (' Ehol ', ' tooooooo@gmail.com ')
Server.starttls ()
Server.login (' Username@gmail.com ', ' password ')

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

e-mail with attachments

To send a message with an attachment, first create the Mimemultipart () instance, and then construct the attachment, which, if there are multiple attachments, can be constructed in sequence and finally sent using SMTPLIB.SMTP
Simulate carrying an attachment in a message, as follows:

Copy Code code as follows:

From Email.mime.text import Mimetext
From Email.mime.multipart import Mimemultipart
Import Smtplib

#创建一个带附件的实例
msg = Mimemultipart ()

txt = Mimetext ("This is Chinese mail content oh", ' plain ', ' gb2312 ')
Msg.attach (TXT)
#构造附件1
ATT1 = Mimetext (open (' D:\\drcom.rar ', ' RB '). Read (), ' base64 ', ' gb2312 '
att1["Content-type"] = ' application/octet-stream '
att1["content-disposition"] = ' attachment; Filename= "Drcom.rar" ' #这里的filename可以任意写, what name to write, what name to show in the mail
Msg.attach (ATT1)

#构造附件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)

#加邮件头
Msg[' to '] = ' tooooooo@qq.com '
Msg[' from '] = ' frommmmmmm@gmail.com '
msg[' subject ' = ' Hello World '




#发送邮件
Try
Server = Smtplib. SMTP ()
Server.connect (' smtp.gmail.com ')
Server.starttls ()
Server.login (' xxxxx@gmail.com ', ' xxxxxxxxx ') #XXX为用户名, xxxxx for password
Server.sendmail (msg[' from '), msg[' to '],msg.as_string ())
Server.quit ()
print ' Send Success '
Except 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.