美文网首页python
Python发送邮件

Python发送邮件

作者: 我是青菜 | 来源:发表于2017-12-01 13:50 被阅读0次

    使用smtplib发送邮件


    def send_email(to_addrs,title,html_text='',mail_text='',enclosure='',cc_addrs=[]):

           # 发送者,标题,html格式文本,文本,附件,抄送,如果附件地址有中文需要解码gbk

         if not to_addrs:

             to_addrs = cc_addrs

            cc_addrs = []

      mail_info = {

    "from": '111111111@163.com',

    "to": to_addrs,

    "CC": cc_addrs,

    "hostname": "smtp.163.com",

    "username": '111111111@163.com',

    "password": '123456',

    "mail_subject":title,

    "mail_text": mail_text,

    "mail_encoding": "utf-8"

    }

    try:

    smtp = SMTP_SSL(mail_info["hostname"])

    except Exception as e:

    logger.error(u'无法连接网络或者邮箱服务器崩溃\n%s'%e)

    return

    # smtp.set_debuglevel(1)

    smtp.ehlo(mail_info["hostname"])

    smtp.login(mail_info["username"], mail_info["password"])

    msg = MIMEMultipart('alternative')

    msg["Subject"] = Header(mail_info["mail_subject"], mail_info["mail_encoding"])

    msg["from"] =  Header('邮件发送平台','utf-8')

    msg["to"] = ','.join(mail_info["to"])

    msg["CC"] = ','.join(mail_info["CC"])

    if html_text:

    part2 = MIMEText(html_text, 'html', mail_info["mail_encoding"])

    msg.attach(part2)

    if mail_text:

    part1 = MIMEText(mail_text, "plain", mail_info["mail_encoding"])

    msg.attach(part1)

    if enclosure:

    part3 = MIMEApplication(open(enclosure,'rb').read())

    part3.add_header('Content-Disposition', 'attachment', filename=os.path.split(enclosure)[1])

    msg.attach(part3)

    smtp.sendmail(mail_info["from"], mail_info["to"], msg.as_string())

    smtp.quit()

    相关文章

      网友评论

        本文标题:Python发送邮件

        本文链接:https://www.haomeiwen.com/subject/futwbxtx.html