Python 电子邮件块中的异常

Exception in Python email block

我的以下代码用于发送带附件的电子邮件。

def email(location):
    COMMASPACE = ', '
    fromaddr = "jeff@abc.com"
    toaddr =  ("jeff@def.com")
    outer = MIMEMultipart()
    outer['Subject'] = 'Dashboard'
    outer['From'] = fromaddr
    outer['To'] = toaddr
    msg = MIMEBase('text','plain')
    msgtext = 'Please find dashboard for the current reporting week.'
    msg.set_payload(msgtext)
    Encoders.encode_base64(msg)
    outer.attach(msg)
    outer.epilogue = ' '
    ctype, encoding = mimetypes.guess_type("parse.mht")
    maintype, subtype = ctype.split('/', 1)
    fp = open(location,'rb')
    msg = MIMEBase(maintype, subtype)
    msg.set_payload(fp.read())
    fp.close()
    Encoders.encode_base64(msg)
    msg.add_header('Content-Disposition', 'attachment', filename='Dashboard.mht')
    outer.attach(msg)
    s = smtplib.SMTP()
    s.connect('mailhost.dev.ch3.s.com')
    s.sendmail(fromaddr, toaddr, outer.as_string(False))
    s.close()
try:
    email(location)
    appendlog.write("Email has been sent, clearing down files... \n")
    print "Email has been sent, clearing down files..."
    success = 1
except Exception,e:
    print repr(e)
    print "Email has failed to send."

我遇到了异常,因为

Typerror("Expected list, got type 'str' ",)

Email has failed to send

谁能告诉我代码有什么问题?

如果您使用 SMTP

toaddr 应该是 list,而不是 tuplestr

或者你可以使用 yagmail,你也可以只发送一个字符串,发送附件也更容易:

import yagmail
fromaddr = "jeff@abc.com"
toaddr =  "jeff@def.com"

yag = yagmail.SMTP(fromaddr, 'yourpassword', host='mailhost.dev.ch3.s.com')

yag.send(toaddr, 'Subject', ['Please find dashboard for the current reporting week.', 
                             '/path/to/local/parse.mht'])

请注意,将文件名添加为字符串会将其转换为附件。