天天看點

python定時發送郵件_Python3實作帶附件的定時發送郵件功能

本文執行個體為大家分享了Python3定時發送郵件功能的具體代碼,供大家參考,具體内容如下

1、 導入子產品

import os

import datetime #定時發送,以及日期

import shutil #檔案操作

import smtplib #郵件子產品

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

from email.header import Header

import time

import 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 = ['[email protected]'] # 收件人郵箱,可以多個(清單形式)群發

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)

以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援腳本之家。