本文實例為大家分享了Python3定時發送郵件功能的具體代碼,供大家參考,具體內容如下
1、 導入模塊
import osimport datetime #定時發送,以及日期import shutil #文件操作import smtplib #郵件模塊from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Headerimport timeimport xlwt #excel寫入
2、寫入EXCEL
def eWrite(fLocate,file_sheet,file_subject,style0): try: if os.path.exists(fLocate): os.remove(fLocate) # 如果文件存在,則刪除 f = xlwt.Workbook(encoding='utf-8') #打開excel文件 fs = f.add_sheet(file_sheet) #sheet名 subject = list(file_subject) #列表化 for i in range(len(subject)): #找到日期列 if '日期' in subject[i]: col_num=i for i in range(len(subject)): #sheet標題 fs.write(0, i, subject[i]) for i in range(10): #單元格寬度為 fs.col(i).width=3333 print("WRITE FINISHED") f.save(fLocate) except : print ("WRITE FAILED")3、發送郵件
def eSend(sender,receiver,username,password,smtpserver,subject,e_content,file_path,file_name): try:#郵件頭 message = MIMEMultipart() message['From'] = sender#發送 message['To'] = ",".join(receiver)#收件 message['Subject'] = Header(subject, 'utf-8') message.attach(MIMEText(e_content, 'plain', 'utf-8'))# 郵件正文# 構造附件 att1 = MIMEText(open(file_path+file_name,'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = "attachment;filename="+file_name message.attach(att1)#執行 smtp = smtplib.SMTP() smtp.connect(smtpserver) #連接服務器 smtp.login(username, password) #登錄 smtp.sendmail(sender, receiver, message.as_string()) #發送 smtp.quit() print("SEND") except: print("SEND FAILED")4、配置與執行
while True:#配置 #__time_____ ehour=11#定時小時 emin=49#定時分鐘 esec=50#定時秒 current_time = time.localtime(time.time()) #當前時間date cur_time = time.strftime('%H%M', time.localtime(time.time())) #當前時間str #__mysql_____ #__email_____ sender = '' # 發件人郵箱 receiver = ['453032441@qq.com'] # 收件人郵箱,可以多個(列表形式)群發 username = '' # 發件人姓名 password = '' # smtp密碼,qq是給你分配一串,163是自己設置 smtpserver = '' # 郵箱服務器 subject = "Hey,here's something interesting" #郵件標題 e_content = '{0:^27}/n{1:^27}/n{2:^25}/n{3:^25}'.format('i','/ //','(-----)','(--------)') #郵件正文 #__file_____ file_path = "D:/" #文件位置 file_name="shit.xls" #文件名 fLocate = file_path + file_name #文件路徑 file_subject='I', 'MISS', 'U' #sheet標題 file_sheet='ok' #sheet名 style0=xlwt.XFStyle() style0.num_format_str='YYYY-MM-DD'#操作 if ((current_time.tm_hour == ehour) and (current_time.tm_min == emin) and (current_time.tm_sec == esec)): print ("START") eWrite(fLocate, file_sheet, file_subject,style0) eSend(sender, receiver, username, password, smtpserver, subject, e_content, file_path,file_name) print(cur_time) time.sleep(1)
新聞熱點
疑難解答