python3自动发送邮件并添加附件

思路

  1. 从数据库读取报表数据
  2. 将报表数据以excel形式存到本地
  3. 将本地报表文件以附件形式添加到邮件发送
  4. 设置定时任务

代码 

import pymysql
import pandas as pd
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication 
import datetime
import schedule,time

def create_report(host,port,user,passwd,db,sql,annex_path):
    '从数据库读取报表数据,以excel形式将报表存到本地'
    conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)# 连接mysql
    cursor = conn.cursor()#创建游标
    cursor.execute(sql)#执行sql语句
    result = cursor.fetchall()#获取执行结果    
    result=[list(x) for x in result]
    col_result = cursor.description  # 获取查询结果的字段描述
    columns=[x[0] for x in col_result]
    data=pd.DataFrame(result,columns=columns)
    data.to_excel(annex_path,index=False)
    cursor.close()#关闭游标
    conn.close()#关闭连接

def send_email(file_name,annex_path):
    '#创建报表和发送邮件'  
    try:
        file_name_new=str(datetime.datetime.now().date())+file_name#根据当前日期拼接附件名称
        annex_path_new=annex_path+'/'+file_name_new  #拼接报表存储完整路径 
        create_report(host,port,user,passwd,db,sql,annex_path_new)#创建报表
        
        #传入邮件发送者、接受者、抄送者邮箱以及主题    
        message = MIMEMultipart()
        message['From'] = sender
        message['To'] = ','.join(receiver)
        message['Cc'] = ";".join(Cc_receiver)
        message['Subject'] = Header(str(datetime.datetime.now().date())+title, 'utf-8')
        
        #添加邮件内容
        text_content = MIMEText(content)
        message.attach(text_content)
        
        #添加附件    
        annex = MIMEApplication(open(annex_path_new, 'rb').read()) #打开附件
        annex.add_header('Content-Disposition', 'attachment', filename=file_name_new)   
        message.attach(annex)

        #image_path = 'C:/Users/yang/Desktop/1.png'
        #image = MIMEImage(open(image_path , 'rb').read(), imageFile.split('.')[-1])
        #image.add_header('Content-Disposition', 'attachment', filename=image_path.split('/')[-1])
        #message.attach(image)
        
        #登入邮箱发送报表
        server = smtplib.SMTP(smtp_ip)#端口默认是25,所以不用指定
        server.login(sender,password)
        server.sendmail(sender, receiver, message.as_string())
        server.quit()
        print('success!',datetime.datetime.now())
        
    except smtplib.SMTPException as e:
        print('error:',e,datetime.datetime.now()) #打印错误
            
if __name__ == '__main__':
#参数设置
    #数据库参数设置
    host='localhost'#数据库ip地址
    port=3306#端口
    user='root'#账户
    passwd='XXX'#密码
    db='XXX'#数据库名称
    sql="SELECT cid,max(score) as max_score FROM sc group by cid;"#报表查询语句
    
    #发送邮件参数设置   
    sender = '[email protected]'#发送者邮箱
    password = 'XXX'#发送者邮箱授权码
    smtp_ip='smtp.126.com'#smtp服务器ip,根据发送者邮箱而定
    receiver = ['[email protected]','[email protected]']#接收者邮箱 
    Cc_receiver=['[email protected]','[email protected]']#抄送者邮箱
    title='订单日报'#邮件主题
    content = 'hello,这是今天的订单日报!'#邮件内容
    file_name='订单日报.xlsx'#报表名称
    annex_path='C:/Users/yang/Desktop/'#报表存储路径,也是附件路径
    ts='10:13'#发送邮件的定时设置,每天ts时刻运行
    
#自动创建报表并发送邮件
    print('邮件定时发送任务启动中.......')
    schedule.every().day.at(ts).do(send_email, file_name,annex_path) # 每天某时刻运行   
    while True:
        schedule.run_pending() # 运行所有可运行的任务
        time.sleep(43200)#因为每次发送邮件的间隔时间是一天左右,所以休眠时间可以设长些

结果 

 

授权码的获取

其中邮箱的授权码不是邮箱的密码,而是邮箱授权给第三方软件登陆邮箱的授权。以QQ邮箱为例,获取授权码步骤如下:

(1)登陆邮箱,点开设置:

(2)选择账户,找到开启SMTP,点击开启:

 

(3)点击开启后,需要本人身份验证:

(4)验证成功后,会出现授权码:

这个授权码,就是要在连接邮件的时候填上。

 附:常用SMTP和POP服务器地址

   1、QQ邮箱(mail.qq.com)
    POP3服务器地址:pop.qq.com(端口:110)
    SMTP服务器地址:smtp.qq.com(端口:25)
    
    2、搜狐邮箱(sohu.com):
    POP3服务器地址:pop3.sohu.com(端口:110)
    SMTP服务器地址:smtp.sohu.com(端口:25)
    
    3、HotMail邮箱(hotmail.com):
    POP3服务器地址:pop.live.com(端口:995)
    SMTP服务器地址:smtp.live.com(端口:587)
    
    4、移动139邮箱:
    POP3服务器地址:POP.139.com(端口:110)
    SMTP服务器地址:SMTP.139.com(端口:25)
    
    5、景安网络邮箱:
    POP3服务器地址:POP.zzidc.com(端口:110)
    SMTP服务器地址:SMTP.zzidc.com(端口:25)
    
    6、新浪邮箱
    smtp.sina.com(端口:25)
    
    7、新浪VIP
    SMTP服务器地址:smtp.vip.sina.com(端口:25)
    
    8、126邮箱
    SMTP服务器地址:smtp.126.com(端口:25)
    
    9、139邮箱
    SMTP服务器地址:smtp.139.com(端口:25)
    
    10、163网易邮箱
    SMTP服务器地址:smtp.163.com(端口:25) 
 

发布了45 篇原创文章 · 获赞 94 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_23860475/article/details/101323705
今日推荐