实现功能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 = """
"""
p = """
大家好:
截止到 """ + get_cpu_report_date(send_date, format_min) + """,各个设备性 能指标报表如下,请查阅。
body = """
""" + p + """"""
html = """""" + head + body + """"""
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 + ""
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
# -*- coding: cp936 -*-
2
3
from email.Header import Header
4
from email.MIMEText import MIMEText
5
from email.MIMEMultipart import MIMEMultipart
6
import smtplib, datetime
7
8
#创建一个带附件的实例
9
msg = MIMEMultipart()
10
11
#构造附件
12
att = MIMEText(open('d:\\tc201.rar', 'rb').read(), 'base64', 'gb2312')
13
att["Content-Type"] = 'application/octet-stream'
14
att["Content-Disposition"] = 'attachment; filename="tc201.rar"'
15
msg.attach(att)
16
17
#加邮件头
18
msg['to'] = 'zhousl@xxx.com'
19
msg['from'] = 'zhousl@xxx.com'
20
msg['subject'] = Header('冒烟测试结果 (' + str(datetime.date.today()) + ')', \
21
'gb2312')
22
#发送邮件
23
server = smtplib.SMTP('smtp.xxx.com')
24
server.sendmail(msg['from'], msg['to'], \
25
msg.as_string())
26
server.close
4、几个值得注意的地方
1)构造附件时注意采用正确的字符集,这个困惑我好久,开始没有用gb2312,发过去的压缩文件就是坏的;
2)上面的代码中没有包括登录smtp服务器的指令,而Internet上面的smtp服务器一般都是要求认证的,可以通过smtp.login方法进行登陆
3)sendmail方法中的参数to可以是包含多个地址的元组,这样可以发送邮件给多个人了
4)Python2.4以前的版本是不支持gb2312字符集的,要下载安装Python2.4才能跑上面的代码,当然2.4.1肯定会更好一点