本文共 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/