显示正文的邮件自动发送

业务场景:

公司最近展开的一项业务中,需要与另一家公司合作,两边就会产生数据方面的交换,需要发送邮件每日更新两边的业务合作的数据情况,毕竟邮件里面会有双方领导在看,所以希望邮件正文内容可以直接显示一些汇总的信息,而不是必须打开附件,显的更professional一点,因此写了如下邮件脚本。

实现过程:

1. 数据查询及导出
数据查询完成后直接导出到本地文件夹,生成csv文件
hive -e ‘sql语句’
在bash中直接通过hive -e命令,并用 > 输出流把执行结果输出到制定文件

2.读取csv文件转成简单的html

import datetime
import codecs
import time
import xlrd
import csv
#将.csv文件转化成.html文件
def csv_to_html(filename,job_table_html):
    table_datas = []
    csvfile = open(filename, encoding = 'utf-8')
    data = csv.reader(csvfile)
    for line in data:
      col = ""
      words=str(line).strip("['']").split('\\x01')
      for i  in words:
          col = col + """
                        <td class="right">%s</td>""" %i
      row = """
              <tr class=" right">
                %s
              </tr>
            """ % col
      table_datas.append(row)
      table_data = ("".join(table_datas))
      html = (
        """
            <style type="text/css">
            .right {text-align: center;}
            .center {text-align: center; font-size:12px;}
            .left {text-align: left;}
            .rightbuttom {text-align: right;}
            table{font-size:15px; margin-top:3px;}
            .table-striped>tbody>tr:nth-child(odd)>td,
            .table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}
            .table-condensed th, .table-condensed td{padding: 2px 3px;vertical-align:middle;}
            </style>

            <table class="table table-hover table-striped table-condensed " border="1" bordercolor="#f9f9f9" cellspacing="0" cellpadding="2" style="border-collapse:collapse">
                <tbody>
                    <tr>
                        <th class="right">日期</th>
                        <th class="right">全部完成数</th>
                        <th class="right">成功结算数</th>
                    </tr>
                    %s
                </tbody>
            </table>
        """ % (table_data))
    open_table = codecs.open(job_table_html,'w+', 'utf-8')
    open_table.writelines(html)
    open_table.close()
    print ("#####################################################################################")
    print ("")
    print ("将.csv文件文件转化成.html文件,转化后.html文件放在%s位置。"%job_table_html)
    now = datetime.datetime.now()
    date = now.strftime('%Y-%m-%d %H:%M:%S')
    print ("Time: %s" %date)
    print ("")
    print ("#####################################################################################")
if __name__ == '__main__':
    #.csv文件位置
    bd_userlogin_csv =("/home/south_hebao_settle_info/hive_result/hebao_cnt.csv")
    #转化后.html文件存放位置
    job_table_html_2 = ("/home/south_hebao_settle_info/hive_result/table_2.html")
    #将.csv文件转化成.html
    csv_to_html(bd_userlogin_csv,job_table_html_2)

3.发送邮件脚本

#coding=utf-8
import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header

def sendMail(sender,reciver,subject,acc,htmlcont):
    smtserver=""
    username=""
    password=""
    msg=MIMEMultipart("related")
    msg['Subject']=email.header.Header(subject,'utf-8')
 #html格式
    html="""%s"""%htmlcont
    htm=MIMEText(html,'html','utf-8')
    msg.attach(htm)
    msg['From']=""
    msg['To']=";".join(reciver)
    msg['Cc'] = ";".join(acc)
 #发送邮件
    #smtp=smtplib.SMTP()
    smtp=smtplib.SMTP_SSL(smtserver, 465)
    smtp.connect("")
    smtp.ehlo()
    #smtp.starttls()
    smtp.login(username, password)
    smtp.sendmail(sender, reciver, msg.as_string())
    smtp.quit()

if __name__=="__main__":
    sender=""#发送人邮箱
    recivers=["",""]#收件人邮箱
    acc=""#抄送人邮箱
    subject=""#邮件主题
    html_path='/home/south_hebao_settle_info/hive_result/table_2.html'
    htmlf=open(html_path,'r',encoding="utf-8")
    htmlcont=htmlf.read()
    sendMail(sender, recivers, subject,acc,htmlcont)
    print ('发送成功')

4. 定时任务自动调度
我们当时是将这些过程封装成了.sh文件,在采用azakaban调度工具进行每日调度任务的

#!/bin/bash
##1-入口参数,获取脚本运行时间参数,默认参数为今天,与当前调度中的参数一致
    echo $#
    
    if [ $# = 0 ]; then
        p_partition_d=`date -d "-1 days" +%Y%m%d`
    fi
    if [ $# = 1 ]; then
        p_partition_d=`date -d "$1" +%Y%m%d`
    fi
    
    echo "p_partition_d:${p_partition_d}" 

base_dir='/home/south_hebao_settle_info'

rm -rf $base_dir/hive_result/*

sh $base_dir/shell/page_conversion_sh.sh ${p_partition_d}

sh $base_dir/hive_to_excel/txt_to_excel.sh

#python3 $base_dir/mail_send/send_email.py

python3 $base_dir/sendemail_content.py

#上传数据到sftp服务器
#sh $base_dir/shell/south_sftp_upload.sh

后来了解到对于轻量型的任务,可以使用shcedule进行定时发送,如下为关于如何使用schedule进行每天9点自动发送邮件的信息:

import schedule
schedule.every().day.at("09:00").do(sendMail(sender,reciver,subject,acc,htmlcont)#,如果sendmail没有参数,则后面的就不需要填写
while True:
    schedule.run_pending()
    time.sleep(60)
    print ('success')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值