在Python中添加Content-Disposition标头 - 电子邮件未发送

时间:2015-09-17 16:23:34

标签: python email

按照Python's email examples中的说明和几个Stack Overflow问题,我编写了以下功能(通过Gmail SMTP服务器发送):

def send_email(emailaddr, message, attachmentfile = None, subject = None):
   try:
        smtpconn = smtplib.SMTP(mainconf["SMTPHOST"], mainconf["SMTPPORT"])
        smtpconn.set_debuglevel(1)
        smtpconn.ehlo()
        smtpconn.starttls()
        smtpconn.login(mainconf["SMTPUSER"], mainconf["SMTPPASS"])
        if not attachmentfile:
           message = '\n' + message
           smtpconn.sendmail(mainconf["EMAILFROM"], emailaddr, message)
        else:
           multipart = MIMEMultipart()
           multipart['Subject'] = subject if subject else "Attachment"
           multipart['From'] = mainconf["EMAILFROM"]  
           multipart['To'] = emailaddr
           with open(attachmentfile, 'rb') as fp:
               filepart = MIMEApplication(fp.read())
           multipart.attach(filepart)
           multipart.attach(message)
           smtpconn.sendmail(mainconf["EMAILFROM"], emailaddr, multipart.as_string())
        generallog.info("Sent an email to {0}".format(emailaddr))
   except:
        generallog.warn("Email sending to {0} failed with error message {1}".format(emailaddr, traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1])))

这适用于发送带附件的电子邮件,但它会产生着名的noname problem(这只是该主题的几个SO问题之一)。所以我补充一点:

  filepart.add_header('Content-Disposition','attachment',filename=os.basename(attachmentfile))

然后Gmail只是拒绝发送电子邮件。当我在Python shell中运行此代码时,我收到标准的message accepted消息,但消息永远不会传递。

为什么会发生这种情况?

0 个答案:

没有答案