博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 发送邮件附件csv_Python 发邮件及邮件附件
阅读量:6502 次
发布时间:2019-06-24

本文共 4114 字,大约阅读时间需要 13 分钟。

#!/usr/bin/env python#-*- encoding:utf-8 -*-

"""@File :mail.py

@time : 2021/1/15 14:22

@Author : huixb"""

#-*- coding: utf8 -*-

importtimeimportdatetimeimportsys, getoptimportsubprocessimporttracebackimportsmtplibfrom smtplib importSMTP_SSLfrom email.header importHeaderfrom email.mime.text importMIMETextfrom email.mime.multipart importMIMEMultipartfrom email.mime.image importMIMEImagefrom email.mime.application importMIMEApplicationimportosimportsys

reload(sys)

sys.setdefaultencoding('utf8')#date_now = time.strftime('%Y-%m-%d',time.strptime(str(datetime.date.today()),"%Y-%m-%d"))

date_now1 = time.strftime('%Y-%m-%d', (datetime.datetime.today() - datetime.timedelta(days=1)).timetuple())

now=datetime.datetime.now()

delta1= datetime.timedelta(days=1)

onedayago= now -delta1

date_now= now.strftime('%Y-%m-%d')

date_1dayago= onedayago.strftime('%Y-%m-%d')#附件名称

filename = 'sell_ribao%s.csv' %date_now1### SQL语句

sql_1= """

"""

##附件头

fileHead = "xx,xx,xx,xx\n".encode("gbk").decode("gbk")#获取hiveSql的结果,输入:sql,输出:结果

defgetHiveSqlResult(sql):

result= ''cmd= 'hive -e """' + sql.replace('"', "\'") + '"""'

#print(cmd)

csvFile2 = ''

try:importcodecs

csvFile2= codecs.open(filename, 'w', 'gbk')

csvFile2.write(fileHead)

p= subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)whileTrue:

buff=p.stdout.readline()if buff == b'' and p.poll() !=None:break

else:

tempStr= buff.decode('utf-8')if tempStr == '':break;

ret= tempStr.find("WARN:", 0, len(tempStr))if ret != -1:break;

tempStr= tempStr.replace('\t', ',')

tempStr= tempStr.encode("gbk").decode("gbk")

csvFile2.write(tempStr)#print(result)

#return result

exceptException as e:print("message is:%s") %(str(e))

traceback.print_exc()finally:

csvFile2.close()#得到html格式的内容

defgetHtmlContent():

getHiveSqlResult(sql_1)

mailtext= u"""本邮件是自动邮件,每日发送。

截止%s本月明细。

数据在附件里。

""" %date_now1#调整表格格式,文字右对齐

mailtext = mailtext.replace('class="dataframe"', 'style="border-collapse: collapse"')

mailtext= mailtext.replace('

', '')returnmailtext#发送邮件

defsendMain(recevEmail, ccEmail, sendEmail, sendPasswd, sendEmailHost, sendMailSubject, sendMailContent):

mailInfo={"from": sendEmail,##"to1" :"xingw@2345.com",

"to": recevEmail,##"to":"wangxr@2345.com",

"cc": ccEmail,"hostname": sendEmailHost,"username": sendEmail,"password": sendPasswd,"mailsubject": sendMailSubject,"mailtext": sendMailContent,"mailencoding": "utf-8"}

mailtext=getHtmlContent()

msg= MIMEMultipart('alternative')

htm= MIMEText(mailtext, 'html', 'utf-8')

msg.attach(htm)

att= MIMEText(open(filename, 'rb').read(), 'base64', 'gbk')

att["Content-Type"] = 'application/octet-stream'att["Content-Disposition"] = 'attachment; filename=%s' %filename

msg.attach(att)

smtp= SMTP_SSL(mailInfo["hostname"])

smtp.set_debuglevel(0)

smtp.ehlo(mailInfo["hostname"])

smtp.login(mailInfo["username"], mailInfo["password"])

msg["Subject"] = Header(mailInfo["mailsubject"], mailInfo["mailencoding"])

msg["from"] = mailInfo["from"]

msg["to"] = mailInfo["to"]

msg['cc'] = mailInfo["cc"]

smtp.sendmail(mailInfo["from"], mailInfo["to"].split(";"), msg.as_string())

smtp.quit()defmain(argv):#收件人邮箱

recevEmail = 'xx@xx.com'

#抄送人邮箱

ccEmail = 'xx@xx.com'

#发送人邮箱账号

sendEmail = 'xx@xx.com'

#发送人邮箱密码

sendPasswd = 'xx'

#邮件服务器

sendEmailHost = 'smtp.exmail.qq.com'

#标题

sendMailSubject = ''

#正文

sendMailContent = ''

if len(argv) < 3:print('vip_loan_refuse_rate.py -r -o -s -p -f -t -c ')

sys.exit(-1)try:

opts, args= getopt.getopt(argv, "hr:o:s:p:f:t:c:a")exceptgetopt.GetoptError:print('vip_loan_refuse_rate.py -r -o -s -p -f -t -c ')

sys.exit(2)for opt, arg inopts:if opt == '-h':print('sxj_loan_refuse_rate.py -r -o -s -p -f -t -c ')

sys.exit()elif opt in ("-r"):

recevEmail=argelif opt in ("-s"):

sendEmail=argelif opt in ("-o"):

ccEmail=argelif opt in ("-p"):

sendPasswd=argelif opt in ("-f"):

sendEmailHost=argelif opt in ("-t"):

sendMailSubject=argelif opt in ("-c"):

sendMailContent=argif len(sendMailContent) <=0:

sendMailContent=getHtmlContent()

sendMailSubject= u"【xxxx(%s)】" %date_now1

sendMain(recevEmail, ccEmail, sendEmail, sendPasswd, sendEmailHost, sendMailSubject, sendMailContent)if __name__ == '__main__':

main(sys.argv[1:])

转载地址:http://pmlyo.baihongyu.com/

你可能感兴趣的文章
3.2 用户组管理
查看>>
ibatis 动态查询
查看>>
汇编语言之实验一
查看>>
git 调用 Beyond Compare
查看>>
SQL基础-->层次化查询(START BY ... CONNECT BY PRIOR)[转]
查看>>
android实现图片识别的几种方法
查看>>
mvc学习地址
查看>>
masonry 基本用法
查看>>
Word产品需求文档,已经过时了【转】
查看>>
dtoj#4299. 图(graph)
查看>>
关于网站的一些js和css常见问题的记录
查看>>
zabbix-3.4 触发器
查看>>
换用代理IP的Webbrowser方法
查看>>
【视频编解码·学习笔记】7. 熵编码算法:基础知识 & 哈夫曼编码
查看>>
spark集群安装部署
查看>>
MySql 查询表字段数
查看>>
mariadb 内存占用优化
查看>>
Centos7安装编译安装zabbix2.219及mariadb-5.5.46
查看>>
怎么获得combobox的valueField值
查看>>
Console-算法[if,while]-一输入两个正整数m和n,求其最大公约数和最小公倍数
查看>>