用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()




你可能感兴趣的:(用Python群发邮件,含附件、excel内容读取,收件人列表读取等)