---
title: "使用python发送html的邮件"
author: "SSTICK"
date: "2013-08-29T09:12:34Z"
tags: []
categories: ["编程语言"]
slug: "python-html"
draft: false
lastmod: "2013-10-30T11:50:47Z"
id: 1933118
url: "https://sstick.iteye.com/blog/1933118"
---

实现功能1：查询数据，然后做成报表，再发送这些报表

 

代码：

写道

import smtplib  
from datetime import datetime, timedelta  
import time  
from email.MIMEText import MIMEText  
from email.MIMEMultipart import MIMEMultipart

def get\_html\_msg(send\_date):  
     head = """&lt;head&gt;&lt;meta charset="utf-8"&gt;  
    &lt;STYLE TYPE="text/css" MEDIA=screen&gt;  
    &lt;!--  
     table {font-size:20px;border-collapse: collapse;font-family: arial;}  
    thead {border: 2px solid #B1CDE3;background: #00ffff;font-size:18px;padding: 10px 10px 10px       10px;color: #4f6b72;font-family: times;}  
     th {vertical-align:top;font-size:12px;padding: 5px 5px 5px 5px;color: #4f6b72;font-family: arial;}  
     body {font-family: arial;}  
    --&gt;  
    &lt;/STYLE&gt;  
    &lt;/head&gt;"""

     p = """&lt;p&gt;大家好：&lt;br&gt;截止到 """ + get\_cpu\_report\_date(send\_date, format\_min) + """,各个设备性     能指标报表如下，请查阅。&lt;br&gt;&lt;/p&gt;"""

     body = """&lt;body&gt;""" + p + """  
     &lt;table border="0" cellpadding="0" cellspacing="0"&gt;  
     &lt;th&gt;""" + get\_cpu\_table() +"""&lt;/th&gt;  
     &lt;th&gt;"""+get\_io\_table() + """&lt;/th&gt;  
     &lt;th&gt;"""+get\_load\_table() + """&lt;/th&gt;  
     &lt;th&gt;"""+get\_memory\_table() + """&lt;/th&gt;  
     &lt;th&gt;"""+get\_process\_speed\_table() + """&lt;/th&gt;  
     &lt;/table&gt;  
     &lt;/body&gt;"""  
     html = """&lt;html&gt;""" + head + body + """&lt;/html&gt;"""  
     return html

def send\_mail(html\_msg):  
     msg = MIMEMultipart()  
     content = MIMEText(html\_msg,'html')  
     msg.attach(content)  
     msg\['To'] = ";".join(to\_list)  
     msg\['From'] = from\_addr  
     msg\['Subject'] = subject  
     s = smtplib.SMTP('xxxx')  
     s.set\_debuglevel(0)  
     s.sendmail(from\_addr, to\_list, msg.as\_string())  
     s.quit()  
     print "ok"

if \_\_name\__ == "\_\_main\_\_":  
     now = datetime.now()  
     html = get\_html\_msg()  
     send\_mail(html)

 

实现功能2(发送附件）：（转载）

 

```
 #!/usr/bin/env python 
#-*-coding:utf8-*- 

import os, smtplib, mimetypes 
from email.mime.text import MIMEText 
from email.mime.image import MIMEImage 
from email.mime.multipart import MIMEMultipart 

MAIL_LIST = ["username@51cto.com"] 
MAIL_HOST = "smtp.51cto.com"
MAIL_USER = "username"
MAIL_PASS = "password"
MAIL_POSTFIX = "51cto.com"
MAIL_FROM = MAIL_USER + "<"+MAIL_USER + "@" + MAIL_POSTFIX + ">"

def send_mail(subject, content, filename = None): 
    try: 
        message = MIMEMultipart() 
        message.attach(MIMEText(content)) 
        message["Subject"] = subject 
        message["From"] = MAIL_FROM 
        message["To"] = ";".join(MAIL_LIST) 
        if filename != None and os.path.exists(filename): 
            ctype, encoding = mimetypes.guess_type(filename) 
            if ctype is None or encoding is not None: 
                ctype = "application/octet-stream"
            maintype, subtype = ctype.split("/", 1) 
            attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype) 
            attachment.add_header("Content-Disposition", "attachment", filename = filename) 
            message.attach(attachment) 

        smtp = smtplib.SMTP() 
        smtp.connect(MAIL_HOST) 
        smtp.login(MAIL_USER, MAIL_PASS) 
        smtp.sendmail(MAIL_FROM, MAIL_LIST, message.as_string()) 
        smtp.quit() 

        return True
    except Exception, errmsg: 
        print "Send mail failed to: %s" % errmsg 
        return False

if __name__ == "__main__": 
    if send_mail("测试信", "我的博客欢迎您/", r"G:\attachment.rar"): 
        print "发送成功！"
    else: 
        print "发送失败！"
```

 1、首先要理解一个常识(RFC)

RFC(The Request for Comments)是一个关于Internet各种标准的文档，定义了很多的网络协议和数据格式，标准的Internet邮件遵从RFC2822(Internet Message Format)等几个文档，其中RFC822中描述了邮件头(mail headers)的格式。具体文档在Python帮助里都可以查到全文。

2、其次要熟悉Python的几个模块

关于邮件的有email，smtplib等，关于编码的有base64，binascii等，发送邮件的方式就是先根据RFC构造好邮件的各个部分，然后登录到smtp服务器sendmail就可以了。

3、下面贴代码

1![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)# -\*- coding: cp936 -\*-

2![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)

3![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)from email.Header import Header

4![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)from email.MIMEText import MIMEText

5![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)from email.MIMEMultipart import MIMEMultipart

6![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)import smtplib, datetime

7![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)

8![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)#创建一个带附件的实例

9![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)msg = MIMEMultipart()

10![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)

11![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)#构造附件

12![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)att = MIMEText(open('d:\\\\tc201.rar', 'rb').read(), 'base64', 'gb2312')

13![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)att\["Content-Type"] = 'application/octet-stream'

14![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)att\["Content-Disposition"] = 'attachment; filename="tc201.rar"'

15![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)msg.attach(att)

16![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)

17![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)#加邮件头

18![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)msg\['to'] = ['](mailto:%20zhousl@xxx.com)zhousl@xxx.com'

19![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)msg\['from'] = ['](mailto:%20zhousl@xxx.com)zhousl@xxx.com'

20![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)msg\['subject'] = Header('冒烟测试结果 (' + str(datetime.date.today()) + ')', \\

21![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)                        'gb2312')

22![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)#发送邮件

23![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)server = smtplib.SMTP('smtp.xxx.com')

24![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)server.sendmail(msg\['from'], msg\['to'], \\

25![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)                 msg.as\_string())

26![使用python发送带附件的邮件（转) - 阿郎 - 阿郎的博客](http://www.cnblogs.com/Images/OutliningIndicators/None.gif)server.close

4、几个值得注意的地方

1)构造附件时注意采用正确的字符集，这个困惑我好久，开始没有用gb2312，发过去的压缩文件就是坏的；

2)上面的代码中没有包括登录smtp服务器的指令，而Internet上面的smtp服务器一般都是要求认证的，可以通过smtp.login方法进行登陆

3)sendmail方法中的参数to可以是包含多个地址的元组，这样可以发送邮件给多个人了

4)Python2.4以前的版本是不支持gb2312字符集的，要下载安装Python2.4才能跑上面的代码，当然2.4.1肯定会更好一点