Python method of using e-mail module smtplib (send picture attachment) practical and feasible

Source: Internet
Author: User
Tags class definition starttls

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 check method, parameters for the user name and password, such as Smtp.login ("[Email protected]", ' 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 ("[Email protected]", ' [email protected] ', body), where the body content is defined as follows:
"" "From:[email protected]
To:[email protected]
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

?
123456789101112131415161718192021222324 [[email protected] smtplib]# cat simple1.py #!/usr/bin/env python# -*- coding: utf-8 -*-import smtplibimport stringHOST = "smtp.139.com" #定义smtp主机SUBJECT = "test" #定义邮件主题TO = "[email protected]" #定义邮件收件人FROM = "[email protected]" #定义邮件发件人text = "python test mail" #邮件的内容BODY=string.join(( #组装sendmail方法的邮件主体内容,各段以"\r\n"进行分隔  "From:%s" %FROM,  "To:%s" %TO,  "Subject:%s"%SUBJECT,  "",  text),"\r\n")   server = smtplib.SMTP() #创建一个SMTP对象server.connect(HOST,"25") #通过connect方法连接smtp主机server.starttls() #启动安全传输模式server.login("[email protected]","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:

?
1234567891011121314151617181920212223242526272829303132333435363738 #!/usr/bin/env python#coding:utf-8import smtplibfrom email.mime.text import MIMEText #导入MIMEText类HOST = "smtp.139.com"SUBJECT = u"官网流量数据报表"TO = "[email protected]"FROM = "[email protected]"msg = MIMEText("""  <table width="800" border="0" cellspacing="0" cellpadding="4">    <tr>      <td bgcolor="#CECFAD" height="20" style="font-size:14px">*官网数据<a href="monitor.domain.com">更多</a></td>    </tr>    <td bgcolor="#EFEBDE" height="100" style="font-size:13px">    1)日访问量:<font color=read>152433</font>访问次数:23651 页面浏览量:45123 点击数:545122 数据流量:504Mb<br>    2)状态码消息<br>      500:105 404;3264 503;214<br>    3)访客浏览器信息<br>      IE:50% firefox:10% chrome:30% other:10%<br>    4)页面信息<br>      /index.php 42153<br>      /view.php 21451<br>    </td>    </tr>  </table>""","html","utf-8")msg[‘Subject‘] = SUBJECTmsg[‘FROM‘] = FROMmsg[‘To‘] = TOtry:  server = smtplib.SMTP()  server.connect(HOST,‘25‘)  server.starttls()  server.login(‘[email protected]‘,‘123456‘)  server.sendmail(FROM,TO,msg.as_string())  server.quit()  print "邮件发送成功"except Exception,e:  print "失败:" + 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:

?
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 #!/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 = "金美美平台系统状态报表" #定义邮件主题TO = "[email protected],[email protected]" #定义邮件收件人FROM = "[email protected]" #定义邮件发件人TO_list = TO.split(TO)def addimg(src,imgid): #添加图片函数,参数1:图片路径,参数2:图片ID  fp = open(src,‘rb‘) #打开文件  msgImage = MIMEImage(fp.read()) #创建MIMEImage对象,读取图片内容并作为参数  fp.close() #关闭文件  msgImage.add_header(‘Content-ID‘,imgid) #指定图片文件的Content-ID,标签src用到  return msgImage #返回msgImage对象 msg = MIMEMultipart(‘related‘) #创建MIMEMultipart对象,采用related定义内嵌资源的邮件体msgtext = MIMEText("""<table width="600" border="0" cellspacing="0" cellspacing="4">  <tr bgcolor="#CECFAD" height="20" style="font-size:14px">  <td colspan=2>以下是211.157.111.41系统状态图</td>  </tr>  <tr bgcolor="#EFEBDE" height="100" 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") #标签的src属性是通过Content-ID来引用的 msg.attach(msgtext) #MIMEMultipart对象附加MIMEText的内容msg.attach(addimg("img/bytes_io.png","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‘] = SUBJECTmsg[‘FROM‘]=FROMmsg[‘To‘] = TOtry:  server = smtplib.SMTP()  server.connect(HOST,"25")  server.starttls()  server.login(‘[email protected]‘,‘123456‘)  server.sendmail(FROM,TO_list,msg.as_string())  server.quit()  print "邮件发送成功!"except Exception,e:  print "失败:"+ str(e)

Code Run effect

Python method of using e-mail module smtplib (send picture attachment) practical and feasible

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.