Python Learning-smtplib Module

Source: Internet
Author: User
Tags class definition starttls email account

Python's Stmplib module enables the sending of messages, which can be emulated by an SMTP client. The python2.3 or later version defaults to the Smtplib module, eliminating the need for additional installation.


I. Common classes and methods of Smtplibi modules

SMTP class Definition: Smtplib ([Host[,port[,local_hostname[,timeout]]), as the constructor of SMTP, the function is to establish a connection with the SMTP server, after the connection is successful, you can send related requests to the server, such as login , check, send, exit and so on. The host parameter is a remote SMTP host address, such as smtp.163.com;port as the connection port, and the default is 25;local_hostname to send the Helo/ehlo (Identity user identity) Directive on the local host's FQDN (the full domain name). Timeout is the number of seconds to connect or try to time out. The SMTP class has the following methods:

Smtp.connect ([Host[,port]]) method

Connect the remote SMTP host method, host is the remote host address, Port is the remote host SMTP port, default 25, can also be directly used in the form of host:port, such as Smtp.connect ("smtp.163.com", "25").

Smtp.login (User,password) method

The remote SMTP host's check method, parameters are user name and password, such as Smtp.login ("[Email protected]", "sdjkg358").

Smtp.sendmail (From_addr,to_addrs,msg[,mail_options,rcpt_options]) method

to implement the message sending function, the parameters are the sender, the recipient, the message content, for example: Smtp.sendmail ("[Email protected]", "[email protected]", body), Where the body content is defined as follows:

"" "From:[email protected]to:[email protected]subject:test mailtest mail Body" "

SMTP.STARTTLS ([Keyfile[,cerfile]]) method

Enable TLS (Secure transport) mode, and all SMTP directives will be encrypted for transmission, such as when using Gmail's SMTP service to start this item to send messages normally, such as SMTP.STARTTLS ().

Smtp.quit () method

Disconnecting the SMTP server


code example-using a TLS connection with a port of 25

#!/usr/bin/python#coding=utf-8import smtplibimport stringhost =  "Smtp.xxxxxxxx.com"  # Define an SMTP host subject =  "Test email from python"   #定义邮件主题TO  =  "[email  Protected] "  #定义邮件收件人FROM  = " [email protected] "  #定义邮件发件人text  = " python  rules them all! "       #邮件内容BODY  = string.join (                  #组装sdemail方法的邮件内容, each section is separated by "\ r \ n"           "from: %s"  % FROM,                    "to: %s"  % TO,          "subject: %s"  % SUBJECT ,          "",         text      & NBsp; ),  "\ r \ n") Server = smtp_ssl ()               #创建一个SMTP () object Server.connect (HOST, "" ")              #通过connect方法连接smtp主机server. STARTTLS ()                      #启动安全传输魔术server. Login ("[email protected]", " Xxxxxxxxxxx ")     #邮箱账号登录校验server. SendMail (from, [to], body)   # Mail Send Server.quit ()                         #断开连接


code example, using the second type of SSL encryption, Port 465, which is the most common way

#!/usr/bin/python#coding=utf-8import smtplibimport stringfrom smtplib import smtp_ssl    #采用SSL加密模块HOST  =  "smtp.xxxxxxxx.com"   #定义smtp主机SUBJECT  =  "Test email  from python "  #定义邮件主题TO  = " [email protected] "  #定义邮件收件人FROM  = " [ Email protected] "  #定义邮件发件人text  = " python rules them all! "       #邮件内容BODY  = string.join (                  #组装sdemail方法的邮件内容, each section is separated by "\ r \ n"           "from: %s"  % FROM,                    "to: %s"  % TO,          "subject: %s"  % SUBJECT ,          "",     &NBsp;   text        ),  "\ r \ n") server =  Smtp_ssl ()              #创建一个SMTP () object, Use SSL encryption Server.connect (HOST, "465")            # Connect the SMTP host via the Connect method Server.login ("[email protected]", "xxxxxxxxxx")    # Email account Login Check Server.sendmail (from, [to], body)    #邮件发送server. Quit ()                        # Disconnect Connection


Second, custom personalized message Format method

The simple text transmitted through the Mail has not been able to meet my needs, such as the need to frequently customize the business quality report, in the message body will contain HTML, images, sounds and attachment format, MIME (Multipurpose Internet Mail Extensions, multi-purpose Internet Mail extension) is the implementation of this. The following are the MIME implementation classes commonly used in Python.

Email.mime.multipart.MIMEMultipart ([_subtype[,bounday[,_subparts[,_params]])

The function is to generate a MIME object that contains multiple parts of the message body, and the parameter _subtype specifies an optional three seed type to add to the "Content-type:multipart/subtype" header, respectively mixed,related,alternative , the default value is mixed. Define the mixed implementation to build a mail body with attachments, define related to construct the message body of the embedded resource, and define the alternative to construct the message body of plain text and hypertext coexistence.

Email,mine.audio.mimeaudio (_audiodata[,_subtype[,_encoder[,**_params]])

Creates a message body containing audio data, _audiodata a byte string containing the raw binary audio data.

Email.mime.image.MIMEImage (_imagedata[,_subtype[,_encoder[,**_params]])

Create a message body containing picture data, _imagedata is a byte string containing the original picture data

Email.mime.text.MIMEText (_text[,subtype[,_charset])

creates a message body containing text data, _text is a string containing the message payload, _subtype the specified text type, supports plain (default), or a string of HTML type


Plain text messages are no longer sufficient for a variety of needs, and the following is a code example that implements HTML-formatted messages by referencing the Email.mime Mimetext class.

#!/usrbin/python#coding: utf-8import smtplibfrom smtplib import smtp_sslfrom  email.mime.text import mimetext    #导入MIMEText类HOST  =  "smtp.xxxxxxxx.com"               #定义smtp主机SUBJECT  = u " Official Website Traffic Data Report "            #定义邮件主题TO  = " [email  Protected] "          #定义邮件收件人FROM  = " [email  Protected] "      #定义邮件发件人msg  = mimetext (" "" "                                                          #创建一个MIMEText对象, specifying HTML content, respectively, Type (text or HTML)     &Lt;table width= " border=" 0 " cellspacing=" 0 " cellpadding=" 4 ">        #字符编码       <tr>         <td bgcolor= "#CECFAD"  height= " style=" font-size:14px ">* official website Data    <a href= "monitor.domain.com" > More >></a></td>       </tr>      <tr>        < Td bgcolor= "#EFEBDE"  height= " style=" "font-size:13px" >         1) Day visits:<font color=red>152433</font>   visits:23651  page views: 45123   Hits:545122   data traffic: 504MB&LT;BR&GT;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;2) Status Code information &LT;BR >        &nbsp;&nbsp;500:105  404:3264   503:214<br>  &nbSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;3) Visitor Browser Information <br>        &nbsp; &nbsp;IE:50%  firefox:10% chrome:30% other:10%<br>      &NBSP;&NBSP;&NBSP;4) page Information <br>        &nbsp;&nbsp;/ index.php 42153<br>        &nbsp;&nbsp;/view.php  21451<br>        &nbsp;&nbsp;/login.php 5112 <br></td>      </tr>    </table> "", "HTML", "Utf-8") msg[' Subject '] = subject   #邮件主题msg [' From ']=from            #邮件发件人, message header visible msg[' to ']=to                #邮件收件人, message header visible Try:    server = smtp_ssl ()     #采用SSL加密模块 &NBsp;   server.connect (HOST, "465")   #通过connect方法连接smtp主机     server.login ("[email protected]", "xxxxxxxxxx")    #邮箱账号登录校验     server.sendmail (from,  to, msg.as_string ())                        #邮件发送     server.quit ()                                                       #断开连接     print  " Message sent successfully! "except exception, e:      print " Failure: "+str (E)

Python Learning-smtplib Module

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.