首页 > 编程语言 > 详细

python 发送邮件 email

时间:2019-05-07 17:09:16      阅读:170      评论:0      收藏:0      [点我收藏+]
import os
import smtplib
import logging
from report_system.utils import excel_util
from report_system.utils import style_util
from email import encoders
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 第三方 SMTP 服务
mail_host = "smtp.mxhichina.com"  # 设置服务器
mail_user = "mail@***.com"  # 用户名
mail_pass = "mima"  # 口令
sender = mail@***.com


def send_files_mail(files, text, title, html=None, receiver=‘name@***.com, content_type=plain, tab=5):
    try:
        """
        发送附件信息
        :param files: 要发送的发送文件的集合信息
        :param title: 要发送的标题
        :param text: 发送的文件的内容
        :param receiver: 想要发送的目标人物  eg: ‘aaa@***.com;bbb@***.com‘
        :param content_type: content_type  默认 plain
        :return:
        """
        # 创建一个带附件的实例
        message = MIMEMultipart()
        message[From] = sender
        message[To] = receiver
        message[Subject] = Header(title, utf-8)
        # 邮件正文内容
        message.attach(MIMEText(text, content_type, utf-8))

        if html:
            message.attach(MIMEText(html, html, utf-8))

        contype = application/octet-stream
        maintype, subtype = contype.split(/, 1)

        for file in files if isinstance(files, list) else str(files).split(;):
            # 构造附件
            data = open(file.strip(), rb)
            file_msg = MIMEBase(maintype, subtype)
            file_msg.set_payload(data.read())
            data.close()
            encoders.encode_base64(file_msg)
            basename = os.path.basename(file)
            file_msg.add_header(Content-Disposition, attachment, filename=basename)
            message.attach(file_msg)

        smtp_obj = smtplib.SMTP_SSL(host=mail_host)  # 注意:如果遇到发送失败的情况(提示远程主机拒接连接),这里要使用SMTP_SSL方法
        smtp_obj.connect(mail_host)
        smtp_obj.login(mail_user, mail_pass)
        smtp_obj.sendmail(sender, str(receiver).strip().split(";"), message.as_string())
        logging.info("邮件发送成功!!!to = {}".format(receiver))
        logging.info("发送成功的文件是 files = {}".format(files))
        smtp_obj.quit()
    except Exception as e:
        if tab > 0:
            logging.error(发送失败!  正在尝试重新发送!请稍等。。。。。。)
            send_files_mail(files, text, title, receiver=receiver, content_type=content_type, tab=tab - 1)
        else:
            logging.exception(e)

 

python 发送邮件 email

原文:https://www.cnblogs.com/bianzhiwei/p/10826121.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!