Python uses the email module Smtplib method _python

Source: Internet
Author: User
Tags class definition starttls

SMPTP class definition: Smtplib. SMTP (Host[,port[,local_hostname[,,timeout]]), as the constructor for SMTP, is the function of establishing a connection with the SMTP server, after the connection is successful, you can send related requests to the server, such as login, checksum, send, exit, etc. The host parameter is a remote SMTP host address, for example, Stmp.163.com;port is a connection port, and the default is 25;local_hostname is to send Helo/ehlo instructions at the local FQDN (full domain name). Timeout for a connection or an attempt to timeout in most seconds, the SMTP class has the following methods:
Smtp.connect ([Host[,port]]) method that connects the remote SMTP host method, host is the remote host address, Port is the remote host SMTP port, default 25, or can be represented directly using the Host:port form, for example: Smtp.connect ("smtp.163.com", "25").
Smtp.login (User,password) method, the validation method for the remote SMTP host, with the user name and password, such as Smtp.login ("18801457794@139.com", ' 123456 ').
Smtp.sendmail (From_addr,to_addrs,msg[,mail_options,rcpt_options]) method to implement the sending function of the message, which is the sender, the recipient, the message content, for example: Smtp.sendmail ("python@163.com", ' 404408853@qq.com ', body), where the body content is defined as follows:
"" "From:python@163.com
To:404408853@qq.com
Subject:test Mail
Test mail Body ""
SMTP.STARTTLS ([Keyfile[,certfile]]) method to enable TLS (secure transfer) mode, all SMTP directives speak encrypted transmissions, such as when using Gmail's STMP server to send messages normally
Smtp.quit () method, port SMTP server connection

Below is an example of how Python sends a message through an instance Lezilai

[Root@localhost smtplib]# cat simple1.py 
#!/usr/bin/env python
#-*-coding:utf-8-*-
import smtplib
Import string
HOST = "smtp.139.com" #定义smtp主机
SUBJECT = "Test" #定义邮件主题 to
= "404408853@qq.com" #定义邮件收件人
from = "18801457794@139.com" #定义邮件发件人
text = "python test Mail" #邮件的内容
body=string.join (#组装sendmail方法的邮件主体内容 , the sections are separated by "\ r \ n"
  %from,
  "to:%s"%to, "
  subject:%s"%subject,
  "",
  text
), "\r\ n ")
   
server = Smtplib. SMTP () #创建一个SMTP对象
server.connect (HOST, "") #通过connect方法连接smtp主机
server.starttls () #启动安全传输模式
Server.login ("18801457794@139.com", "123456") #邮件账户登录校验
server.sendmail (from,to,body) #邮件发送
server.quit () #断开smtp连接

To execute this code, we will receive an email

To implement a data report message in HTML format
The text-only message content has not been able to meet our diverse needs, and this example enables HTML-formatted messages by introducing the Email.mime Mimetex class, supporting all HTML elements, including tables, pictures, animations, CSS styles, forms, and so on. This example uses the HTML table to customize the perfect Business Traffic report, implementing the following code:

#!/usr/bin/env python #coding: utf-8 import smtplib from email.mime.text import mimetext #导入MIMEText类 HOST = "smtp.139.com "SUBJECT = u" official Website traffic Data Report "to =" 404408853@qq.com "from =" 18801457794@139.com "msg = Mimetext (" "" <table width= "," bo Rder= "0" cellspacing= "0" cellpadding= "4" > <tr> <td bgcolor= "#CECFAD" height= "style=" font-size:14 PX ">* official website Data <a href=" monitor.domain.com "> More </a></td> </tr> <td bgcolor=" #EFEBDE "height = "style=" font-size:13px "> 1" Day visits: <font color=read>152433</font> Hits: 23651 page Views: 45,123 clicks : 545122 Data Flow:504mb<br> 2) Status code message <br>   500:105 404;3264 503;214<br> 3) Visitor Browser Information <br&
    Gt   ie:50% firefox:10% chrome:30% other:10%<br> 4) page information <br>   /index.php 42153<br&
    Gt    /view.php 21451<br> </td> </tr> </table> "" "," html "," Utf-8 ") msg[' Subject '] = SUBJECT msg[' FROM '] = from msg["to" = to Try:server = Smtplib. SMTP () server.connect (HOST, ' ") Server.starttls () server.login (' 18801457794@139.com ', ' 123456 ') server.sendmail (FR Om,to,msg.as_string ()) server.quit () print "Mail sent successfully" except Exception,e:print "failed:" + str (e)

Run code results as shown in the diagram,

Example 2: Server performance report messages implemented in a graphic format
When you require a message content that contains picture data, you need to refer to the Mimeimage class, and if the message body consists of multiple MIME objects, you need to refer to the Mimemultipart class to encapsulate it. This example uses a combination of Mimetext and Mimeimage classes to customize the server performance report message in a graphic format, implementing the following code

#!/usr/bin/env python #coding: utf-8 import smtplib,string from Email.mime.multipart import Mimemultipart from Email.mime . Text import Mimetext from email.mime.image import mimeimage HOST = "smtp.139.com" #定义smtp主机 SUBJECT = "Golden Meimei Platform System Status Report" #定义邮件主 Title to = "404408853@qq.com,302803690@qq.com" #定义邮件收件人 from = "18801457794@139.com" #定义邮件发件人 to_list = To.split (TO) def Addim G (Src,imgid): #添加图片函数, Parameter 1: Picture path, parameter 2: Picture id fp = open (src, ' rb ') #打开文件 msgimage = Mimeimage (Fp.read ()) #创建MIMEImage对象, read inside the picture The volume is also used as a parameter fp.close () #关闭文件 msgimage.add_header (' Content-id ', Imgid) #指定图片文件的Content-id, label SRC to return Msgimag E #返回msgImage对象 msg = Mimemultipart (' related ') #创建MIMEMultipart对象, message body with related definition embedded resources Msgtext = Mimetext ("" "<table W Idth= "border=" "0" cellspacing= "0" cellspacing= "4" > <tr bgcolor= "#CECFAD" height= "style=" > &LT;TD colspan=2> Below is 211.157.111.41 System state diagram </td> </tr> <tr bgcolor= "#EFEBDE" height= "style=" font-size:13px "> <td> </td><td> </td> </tr> <tr Bgcol Or= "#EFEBDE" height= "style=" "font-size:13px" > <td> </td><td> <i MG src= "Cid:disk" ></td> </tr> </table> "" "," html "," Utf-8 ") # The SRC attribute of the label is Msg.attach (Msgtext) #MIMEMultipart对象附加MIMEText的内容 Msg.attach (addimg ("Img/bytes_io.png"), which is referenced by Content-id. "IO") #使用MIMEMultipart对象附加MIMEImage的内容 Msg.attach (addimg ("Img/os_load.png", "Load")) Msg.attach (Addimg ("Img/os_
Mem.png "," mem ") Msg.attach (addimg (" Img/os_disk.png "," Disk ")) msg[' Subject '] = Subject msg[' from ']=from msg[' to '] = to Try:server = Smtplib. SMTP () Server.connect (HOST, "") Server.starttls () server.login (' 18801457794@139.com ', ' 123456 ') server.sendmail (FR Om,to_list,msg.as_string ()) server.quit () print "Message sent successfully!" except Exception,e:print failed: "+ str (e)

The code works as shown

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.