python_email

# coding=utf-8

import smtplib
from email.mime.multipart import MIMEMultipart  #发送多个文件使用
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication


def send_email(content, filepath, receivers, ):
    # 第三方 SMTP 服务
    mail_host = "smtp.163.com"  # 设置服务器
    mail_user = "trsch.om"  # 用户名
    mail_pass = "HUFVVJ"  # 口令

    message = MIMEMultipart()
    message['Subject'] = content  # 标题
    message['From'] = mail_user  # 来源
    if len(receivers) > 1:
        message['To'] = ','.join(receivers)  # 群发邮件
    else:
        message['To'] = receivers[0]

    # 内容
    part = MIMEText(content)
    message.attach(part)

    #文件
    xls = MIMEApplication(open(filepath, 'rb').read())
    xls.add_header('Content-Disposition', 'attachment', filename='nginx_out.xlsx')
    message.attach(xls)

    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(mail_host)  # 25 为 SMTP 端口号
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(mail_user, receivers, message.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException:
        import traceback

        traceback.print_exc()
        print("无法发送邮件")


if __name__ == '__main__':
    send_email("nginx", "./1.xlsx", ["Zbb@qq.com"])

posted @ 2021-10-14 18:42  追梦nan  阅读(57)  评论(0编辑  收藏  举报