SMPTP class definition: Smtplib. SMTP (Host[,port[,local_hostname[,,timeout]]), as the constructor of SMTP, the function is to establish a connection with the SMTP server, after the successful connection, 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 stmp.163.com;port for a connection port, and the default is 25;local_hostname to send Helo/ehlo instructions on the local FQDN (full domain name). Timeout is a connection or attempt to time out in most seconds, 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, for example: Smtp.connect ("smtp.163.com", "25").
Smtp.login (User,password) method, the remote SMTP host's check method, parameters for 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 message sending function, the parameters are 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, enable TLS (secure transport) mode, all SMTP instructions are encrypted, such as the use of Gmail's STMP server need to start this to send mail normally
Smtp.quit () method, connection to the Port SMTP server
Here's an example of how Python sends messages Lezilai
[Root@localhost smtplib]# cat simple1.py #!/usr/bin/env python#-*-coding:utf-8-*-import smtplibimport stringHOST = "SM tp.139.com "#定义smtp主机SUBJECT =" Test "#定义邮件主题TO =" 404408853@qq.com "#定义邮件收件人FROM =" 18801457794@139.com "#定义邮件发件人text =" Python test Mail "#邮件的内容BODY =string.join (#组装sendmail方法的邮件主体内容, each section is" \ r \ n "Separated " from:%s "%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连接
Execute this code, we will receive an email
Implementing HTML-formatted data report messages
Plain text mail content has not been able to meet our diverse needs, this example through the introduction of the Email.mime Mimetex class to implement HTML-enabled messages, support all HTML elements, including tables, images, animations, CSS styles, forms and so on. This example uses HTML tables to customize the perfect business Traffic report with the following code:
#!/usr/bin/env python#coding:utf-8import smtplibfrom 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=" "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> <td bgcolor= "#EFEBDE" height= "[Sty]" le= "font-size:13px" > 1) Day visits: <font color=read>152433</font> Hits: 23651 page Views: 45,123 Hits: 545122 Data traffic :504mb<br> 2) Status code message <br> 500:105 404;3264 503;214<br> 3) Visitor Browser information <br> ie:50% firefox:1 0% chrome:30% other:10%<br> 4) page Info <br>/index.php 42153<br>/view.php 21451<br> &L t;/td> </tr> </table> "", "html", "Utf-8") msg[' Subject '] = subjectmsg[' from '] = frommsg[' to '] = totry:s erver = Smtplib. SMTP () Server.conneCT (HOST, ' Server.starttls ') server.login (' 18801457794@139.com ', ' 123456 ') server.sendmail (from,to,msg.as_ String ()) Server.quit () print "message sent successfully" except Exception,e:print "failed:" + str (e)
Run code results,
Example 2: Implementing a graphics-formatted server performance report message
When a message content containing picture data needs to be referenced, a reference to the Mimeimage class is required, and if the message body consists of multiple MIME objects, it is also necessary to reference the Mimemultipart class for encapsulation. This example uses the combination of the Mimetext and Mimeimage classes to customize the server performance report messages in the graphics format, with the following code implementation:
#!/usr/bin/env python#coding:utf-8import smtplib,stringfrom email.mime.multipart Import Mimemultipartfrom Email.mime.text Import mimetextfrom email.mime.image Import mimeimagehost = "smtp.139.com" #定义smtp主机SUBJECT = " Golden Meimei Platform System Status Report "#定义邮件主题TO =" 404408853@qq.com,302803690@qq.com "#定义邮件收件人FROM =" 18801457794@139.com "#定义邮件发件人TO_list = To.split (TO) def addimg (Src,imgid): #添加图片函数, Parameter 1: Picture path, parameter 2: Picture id fp = open (src, ' rb ') #打开文件 msgimage = Mimeimage (Fp.read ()) # Create a Mimeimage object, read the picture content and act as a parameter fp.close () #关闭文件 msgimage.add_header (' Content-id ', imgid) #指定图片文件的Content-id, The label SRC uses the return msgimage #返回msgImage对象 msg = Mimemultipart (' related ') #创建MIMEMultipart对象, using related to define the embedded resource's message body Msgtext = Mimetext ("" "" <table width= "" border= "0" cellspacing= "0" cellspacing= "4" > <tr bgcolor= "#CECFAD" height= "20" style= "font-size:14px" > <td colspan=2> the following is 211.157.111.41 System state diagram </td> </tr> <tr bgcolor= "# Efebde "height=" style= "font-size:13px" > <td> </td><td> </td> </tr> <tr bgcolor=" #EFEBDE "height=" 100 " style= "font-size:13px" > <td> </td><td> < /td> </tr> </table> "" "," html "," Utf-8 ") # the src attribute of the tag is referenced by Content-id to Msg.attach (msgtext) # Mimemultipart Object Append mimetext content Msg.attach (addimg ("Img/bytes_io.png", "IO")) # Use the Mimemultipart object to attach mimeimage content 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 '] = subjectmsg[' from ']=frommsg[' to '] = Totry: Server = Smtplib. SMTP () Server.connect (HOST, "Server.starttls") server.login (' 18801457794@139.com ', ' 123456 ') server.sendmail ( From,to_list,msg.as_string ()) server.quit () print "Mail sent successfully!" Except Exception,e:print "failed:" + str (e)
Code Run effect