Python电子邮件块中的异常

时间:2015-12-07 12:56:17

标签: python email mime

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

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("预期列表,类型' str'",)

     

电子邮件无法发送

有人能告诉我代码中有什么问题吗?

1 个答案:

答案 0 :(得分:1)

如果您使用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'])

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