2020-05-14 Python_sendMail 带附件发邮件

    恩,最近自学Python.在度娘和的帮助下成功完成Python STMP 在阿里云服务器自动发邮件,用于自动定时给指定领导发送报表,邮件发送代码如下:


#encoding=utf8

import smtplib

import datetime

from email.mime.multipart import MIMEMultipart

from email.header import Header

from email.mime.text import MIMEText

from email.mime.application import MIMEApplication

def send_email(to_addr, msg_subject,file_name,cc_addr=None,file_path=None):

    """

    to_addr: 收件人的邮箱地址, 例如 {‘[email protected]','[email protected]'}

    msg_subject: str, 邮件的标题

    cc_addr: dict, 抄送人的邮箱昵称和地址, 例如 {'[email protected]','[email protected]'}

    file_path: str, 附件文件路径

    """

    # 第三方 SMTP 服务

    mail_host = "smtp.qiye.aliyun.com"  # 设置服务器

    mail_user = "XXXXXXXXX"  # 用户名

    mail_pass = "XXXXXXXXX"  # 口令

    sender = '[email protected]'  # 发件人

    receivers = to_addr  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

    # 邮件内容

    content = MIMEText(''' 

    -----------------------------------------------------------------------

    自动报表

    -----------------------------------------------------------------------


                主要内容请查看附件XLS                                                                                                                     


    -----------------------------------------------------------------------

    本邮件由系统自动发送,请勿回复。

    -----------------------------------------------------------------------

    ''')

    message = MIMEMultipart()

    message.attach(content)

    message['From'] = '[email protected]'      # 发件人

    print(to_addr)

    message['To'] = to_addr                    # 收件人

    if cc_addr is not None:

        message['Cc'] = cc_addr  # 抄送人

    subject = msg_subject

    message['Subject'] = Header(subject, 'utf-8')

    xlsx = MIMEApplication(open(file_path, 'rb').read())

    xlsx["Content-Type"] = 'application/octet-stream'

    xlsx.add_header('Content-Disposition', 'attachment', filename=file_name)

    message.attach(xlsx)

    try:

        smtpObj = smtplib.SMTP()

        smtpObj = smtplib.SMTP_SSL(mail_host,465)      # SSL方式发送 端口号465 因阿里云25端口号封所以改用465

        smtpObj.login(mail_user, mail_pass)         

        smtpObj.sendmail(sender, receivers, message.as_string())

        print("邮件发送成功")

    except  Exception as e:

        print(e)

if __name__ == "__main__":

    to_addr = [email protected] # 收件人地址

    cc_addr = [email protected] # 抄送人地址多个地址,号隔开

    msg_subject = '我是邮件标题'

    file_path = "D:\\PySendMailrpot\\2020-05-14商品信息变更.xlsx"

    today = datetime.date.today()

    file_name=str(today)+'商品信息变更.xlsx'

    send_email(to_addr, msg_subject,file_name,cc_addr=None,file_path=None)

你可能感兴趣的:(2020-05-14 Python_sendMail 带附件发邮件)