定时发送邮件附件

# -*- coding: utf-8 -*-                                                                                                                                 
import sys,os
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication 

mail_host ="smtp.exmail.qq.com"                                                                                                               
mail_user = ""
mail_pass = "xxx"

content = "各位同事大家好,这是%s的数据报表" %(datetime.datetime.now().strftime("%Y %m %d"))
textApart = MIMEText(content)
ExcelFile = '数据报表-%s' %(datetime.datetime.now().strftime('%Y-%m-%d'))
ExcelApart = MIMEApplication(open(ExcelFile, 'rb').read())
ExcelApart.add_header('Content-Disposition', 'attachment', filename=ExcelFile)


def sendmail(receiver):                                                                                                                                         
    u"""发送邮件."""
    
    os.chdir(r"D:\运维资料\script\数据导出")
    message = MIMEMultipart()
    message.attach(textApart)
    message.attach(ExcelApart)
    message['Subject'] = Header("数据报表", 'utf-8')
    
    try
        smtpObj = smtplib.SMTP_SSL(mail_host,465)
        smtpObj.ehlo()
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(mail_user, receiver,message.as_string())
        smtpObj.quit()
        Logfile = open(r'log\send-email.log', 'a')
        Logfile.write("[" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "]" + " INFO:" + " send email success.\n")
        Logfile.close()
        print("sendmail  success. ")
    except Exception as e:
            Logfile = open(r'log\send-email.log', 'a')
            Logfile.write("[" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "]" + " ERROR:" + " send email failed.\n")
            Logfile.close()
            sys.exit(1)

你可能感兴趣的:(定时发送邮件附件)