1. 程式人生 > >用Python群發郵件,含附件、excel內容讀取,收件人列表讀取等

用Python群發郵件,含附件、excel內容讀取,收件人列表讀取等

11月13日更新:把所有部分函式化

環境:Python 3.6

from openpyxl import load_workbook #excel
import datetime
from smtplib import SMTP #郵件
from time import sleep
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase #附件
from email import encoders #轉碼

#獲得昨天的日期,並把名字改成0901這樣的格式
def getYesterday(): today = datetime.date.today() oneday = datetime.timedelta(days = 1) yesterday = today - oneday date_yes = yesterday.strftime("%m%d") return date_yes #獲得日報的標準名稱 def get_ribao(): ribao_name = '【基礎經營-實體1】:“乘風破浪”百日衝刺報表'+getYesterday()+'.xlsx' ribao_title =
'請收閱:'+'【基礎經營-實體1】:“乘風破浪”百日衝刺報表'+getYesterday() return ribao_name, ribao_title # print(ribao_name) # print(ribao_title) #從日報中獲取郵件正文內容 def get_ribao_value(ribao_name): wb = load_workbook(ribao_name) sheet1 = wb['門店通報'] body = sheet1['A2'].value + '\n\n' + '注:這封郵件是通過python傳送,通過網頁端可正常顯示;outlook可能會附件為.dat格式,無法開啟;foxmail低版本可能無法收到附件,升級到7.2及以上即可!'
return body # print(body) #讀取收件人列表 def get_receiver(sheetname): receive_list = [] receive_mail = load_workbook(filename='/Users/Administrator/Desktop/報表/日報/日報收件人.xlsx') sheet = receive_mail[sheetname] max_row = sheet.max_row + 1 for rowNum in range(2, max_row): receive_list.append(sheet.cell(row=rowNum,column=2).value) return receive_list #開始新增附件了 def put_attachment(ribao_name): with open(ribao_name,'rb') as f: #這裡附件的MIME和檔名,這裡是xlsx型別 mime = MIMEBase('xlsx','xlsx',filename=ribao_name) #加上必要的頭資訊 mime.add_header('Content-Disposition','attachment',filename=('gb2312', '', ribao_name)) mime.add_header('Content-ID','<0>') mime.add_header('X-Attachment-Id','0') #把附件的內容讀進來 mime.set_payload(f.read()) #用Base64編碼 encoders.encode_base64(mime) msg.attach(mime) #開始email板塊了 def main(): receive_list = get_receiver('收件人') chaosong_list = get_receiver('抄送人') fromAddr = '******' #發件人 myPass = '******' #發件人密碼 if len(receive_list) == 0: toAddr = '' else: toAddr = ','.join(receive_list) #收件人 if len(chaosong_list) == 0: acc = '' else: acc = ','.join(chaosong_list) #抄送人 ribao_name = get_ribao()[0] ribao_title = get_ribao()[1] body = get_ribao_value(ribao_name) global msg msg = MIMEMultipart() msg['From'] = fromAddr msg['To'] = toAddr msg['Subject'] = ribao_title msg['Cc'] = acc msg.attach(MIMEText(body)) put_attachment(ribao_name) server = SMTP('mail.sh.ctc.com') server.starttls() server.login(fromAddr, myPass) server.send_message(msg) server.quit() print("日報已經發送完成!") sleep(3) if __name__ =="__main__": main()