【Python】解决发送多人邮件没有展示收件人的问题

背景:

工作过程中需要对现有的机器、服务做监控,当服务出现问题后,邮件通知对应的人

问题:

使用python 2.7自带的email库来进行邮件的发送,但是发送后没有展示收件人列表内容

问题代码示例:

# -*- coding:utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_email_to(fromAdd, toAdd, subject, html_text, filename):
    server = 'mail.****.com'
    user = '*****'
    password = '********'

    strFrom = fromAdd
    strTo = toAdd

    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    msgText = MIMEText(html_text, 'html', 'utf-8')
    msgAlternative.attach(msgText)

    smtp = smtplib.SMTP()
    smtp.connect(server)
    smtp.login(user, passwd)

    att5 = MIMEText(open(filename, 'rb').read(), 'base64', 'utf-8')
    att5["Content-Type"] = 'application/octet-stream'
    att5["Content-Disposition"] = 'attachment; filename="fail_7_storage.txt"'
    msgRoot.attach(att5)

    smtp.sendmail(strFrom, strTo, msgRoot.as_string())
    smtp.quit()
    return

成功代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr
from email.utils import formataddr
from email.header import Header


def __format_addr__(addr):
    # 解析邮件地址,以保证邮有别名可以显示
    alias_name, addr = parseaddr(addr)
    # 防止中文问题,进行转码处理,并格式化为str返回
    return formataddr((Header(alias_name,charset="utf-8").encode(),
                       addr.encode("uft-8") if isinstance(addr, unicode) else addr))


def send_email_to(fromAdd, toAdd, subject, html_text, filename=None):

    SERVER = 'mail.***.com'
    USER = '******'
    PASSWD = '***'

    strFrom = __format_addr(fromAdd)

    strTo = list()
    # 原来是一个纯邮箱的list,现在如果是一个["jayzhen"]的list给他格式化
    try:
        for a in toAdd:
            strTo.append(__format_addr(a))
    except Exception as e:
        # 没有对a和toadd进行type判断,出错就直接还原
        strTo = toAdd

    msgRoot = MIMEMultipart('related')
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    # 邮件对象 
    msgText = MIMEText(html_text, 'html', 'utf-8')
    msgRoot['Subject'] = Header(subject)   # 这是邮件的主题,通过Header来标准化
    msgRoot['From'] = strFrom       # 发件人也是被格式化过的
    msgRoot['to'] = ','.join(strTo)   # 这个一定要是一个str,不然会报错“AttributeError: 'list' object has no attribute 'lstrip'”
    msgAlternative.attach(msgText)

    smtp = smtplib.SMTP(SERVER, 11)
    smtp.set_debuglevel(0)
    # smtp.connect(SERVER)
    smtp.login(USER, PASSWD)
    # 这里要注意了,这里的fromadd和toAdd和msgRoot['From'] msgRoot['to']的区别
    smtp.sendmail(fromAdd, toAdd, msgRoot.as_string())
    smtp.quit()

总结:

看到 msgRoot['to'] = ','.join(strTo)  与  msgRoot['to'] = strTo

实验过程中发现这个["to"]一定要是一个str,不然会报错“AttributeError: 'list' object has no attribute 'lstrip'”

同时也发现["to"]的数据类型与sendmail(from_addrs,to_addrs,...)的to_addrs不同;前者为str类型,多个地址使用逗号分隔,后者为list类型

还有就是MIMEText、MIMEMultipart他们之间的关系,可以看一哈源码,他们算是兄弟关系,都是继承MIMEBase,那么这是时候,["From"]、["to"]等这些属性给谁都行。

你可能感兴趣的:(#,Python,python,email)