#!/usr/bin/python
# -*- coding: utf-8 -*- #此处支持中文字符一定要放在前两行,置后的话不生效,脚本报错
#!/usr/bin/env python


import smtplib

from email.mime.text import MIMEText

import string
import time
import datetime


 
HOST = "mail.xxxxxx.com" #smtp主机地址
 
SUBJECT_1 = "xxx数据推送"#邮件标题
SUBJECT_1=unicode(SUBJECT_1,'utf-8') #转码成中文,否则推到邮箱显示为乱码
 

TO = ['xxx@xxx.com','xxx@qq.com'] #定义邮件收件人
FROM = "xxx@xxx.com" #定义邮件发件人
 
TIME_NOW = time.strftime("%Y%m%d",time.localtime()) #获取系统当前时间格式为年月日
 
NOW_TIME = datetime.datetime.now() #
TIME = NOW_TIME + datetime.timedelta(days=-1)#
TIME_YES = TIME.strftime('%Y%m%d') #获取系统昨日时间,格式为年月日
 
 
TITLE="xxx_"+TIME_YES+"_12:00-"+TIME_NOW+"_12:00"+".csv" #定义邮件文件名,这里用到了自动获取昨日日期和今日日期作为文件名的一部分,具体效果为:

                                xxx_20160708_1500-20160710_1200


#创建一个MIMEText对象,附加name.txt文档

attach_1 = MIMEText(open("name.txt","rb").read(),"base64","utf-8") #打开name.txt文件
attach_1["Content-Type"] = "application/octet-stream" #指定文件格式类型

#指定Content-Disposition值为p_w_upload则出现下载保存对话框,保存的默认文件名使用filename指定

attach_1["Content-Disposition"] = "p_w_upload; filename="+TITLE

#比如qqmail使用gb18030页面编码,为了保证收到邮件时,中文文件名不出现乱码,需要对文件名进行编码转换

decode("utf-8").encode("gb18030")

 
 
msg_1 = MIMEMultipart('related')
msg_1.attach(attach_1) #MIMEMultipart对象附加MIMEText附件内容
msg_1['Subject'] = SUBJECT_1 #邮件主题
msg_1['From'] = FROM #邮件发件人,邮箱头部可见

#msg_1['TO'] = TO #邮件收件人,邮件头部可见,可有可无
try:
    server = smtplib.SMTP() #创建一个SMTP()对象
    server.connect(HOST,"25") #通过connect方法连接smtp主机
    server.starttls() #启动安全传输模式
    server.login('name','mypassword')#邮箱账号登录校验
    server.sendmail(FROM,TO,msg_1.as_string()) #邮件发送
    server.quit() #断开smtp连接
    print "success!"
except Exception, e:
    print "fail:"+str(e)