您的位置:首页 > 编程语言 > Python开发

python中发送邮件各种问题

2015-09-06 12:12 507 查看
其实问题主要集中的QQ企业邮箱中,特别坑爹。。。代码如下:

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText

# python 2.3.*: email.Utils email.Encoders
from email.utils import COMMASPACE,formatdate
from email import encoders

import os
import datetime

uploadlogPath = "/home/harklee/shell/data"
curDate = datetime.datetime.now()
curDateFormat = curDate.strftime("%Y-%m-%d")
lastDate = curDate + datetime.timedelta(days = -1)
lastDateFormat = lastDate.strftime("%Y-%m-%d")
server = {"name":"smtp.exmail.qq.com", "user":"xx@xx.com", "passwd":"password"}   #注意,QQ企业邮箱中, user必须是全称的帐号,就是要带上@后缀,个人邮箱则不需要 name是smtp的地址
fro = "xx@xx.com"   #发件人邮箱
to = ["xx@xx.com","xxx@qq.com"]   #收件人邮箱
subject = "数据每日日报"     #发送标题
text = "数据每日日报,目前因为数据体系还没有开始搭建,所以指标很简单,目前为两分部,第一部分是建议运营指标,第二部分是接口监测指标,压缩文件是以日志日期命名的:\n\n运营指标:\n1) 当天去重后的imei数据,格式是yyyy-MM-dd_imei.log \n2) 当天去重后的imei_app数据,格式是yyyy-MM-dd_app.log \n\napi接口监测指标 \n 1)每小时的数据流量行数 格式是yyyy-MM-dd_hour_line.log \n 2)监测每秒的最大并发数 格式是yyyy-MM-dd_second_max_line.log"  #发送内容
files = [uploadlogPath+"/"+lastDateFormat+".tar.gz"]   #要发送的附件啦
#print files

#server['name'], server['user'], server['passwd']
def send_mail(server, fro, to, subject, text, files=[]):
assert type(server) == dict
assert type(to) == list
assert type(files) == list

msg = MIMEMultipart(_charset='utf-8')   #这里注意编码

msg['From'] = fro
msg['Subject'] = subject
msg['To'] = COMMASPACE.join(to) #COMMASPACE==', '
msg['Date'] = formatdate(localtime=True)
msg.attach(MIMEText(text,_charset='utf-8'))    #这里也要注意编码

for file in files:
part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data
part.set_payload(open(file,'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(part)

import smtplib
smtp = smtplib.SMTP(server['name'])
smtp.login(server['user'], server['passwd'])
smtp.sendmail(fro, to, msg.as_string())
smtp.close()

send_mail(server,fro,to,subject,text,files)


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: