有python构建电子邮件的麻烦

时间:2011-10-21 18:57:32

标签: python email

我使用email.mime库为我的客户开发了一个电子邮件系统。我为一些邮件客户端工作得非常好。例如在gmail上我可以看到html正文和附件文件但是在yahoo上我收到一封空邮件。这是代码:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
import email.charset

from email import Encoders
def buildEmail(from_email, to_email, subject, text_msg, html_msg, attach_pdf_file):
    """
    This function build a body for text/html message and if attachment file provide
    then it will attach it too with email.
    """

    # Create message container - the correct MIME type is multipart/alternative.

    msgRoot = MIMEMultipart('alternative')
    msgRoot['Subject'] = subject

    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    msgRoot.epilogue = ''


    # Record the MIME types of both parts - text/plain and text/html.
    text_part = MIMEText(text_msg, 'plain')
    msgRoot.attach(text_part)

    if html_msg is not None and html_msg != '':
        html_part = MIMEText(html_msg, 'html')
        msgRoot.attach(html_part)


    # Attach a file if provided
    if attach_file is not None and attach_file != '':
        fp = open(attach_pdf_file, 'rb')
        part = MIMEBase('application', 'pdf')
        part.set_payload( fp.read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename="%s"%          os.path.basename(attach_pdf_file))
        msgRoot.attach(part)
        fp.close()


    s = smtplib.SMTP('localhost')
    s.sendmail(from_email, to_email, msgRoot.as_string())
    s.quit()

知道我哪里弄错了吗?

1 个答案:

答案 0 :(得分:0)

我看到这个代码有几个问题,应该阻止它在Python 2.x上运行。

1)你没有在任何地方定义attach_file,所以这一行引发了一个异常:

if attach_file is not None and attach_file != '':

您的意思是attach_pdf_file吗?将attach_file更改为attach_pdf_file会更正该异常。

2)也许您只是将其从代码示例中删除,但是您从os.path调用了一个函数,但在脚本中的任何地方都没有import os。添加可以纠正该异常。

一旦纠正了这些问题,在我的系统上使用from地址作为gmail地址运行脚本会引发此异常:

Traceback (most recent call last):
  File "/home/ra/Desktop/stack-overflow.py", line 50, in <module>
    "output.pdf")
  File "/home/ra/Desktop/stack-overflow.py", line 44, in buildEmail
    s = smtplib.SMTP('localhost')
  File "/usr/lib/python2.7/smtplib.py", line 249, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python2.7/smtplib.py", line 309, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python2.7/smtplib.py", line 284, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "/usr/lib/python2.7/socket.py", line 571, in create_connection
    raise err
error: [Errno 111] Connection refused

我没有在本机上本地配置SMTP服务器,这解释了我收到错误的原因。在您的情况下,如果电子邮件发送正确,但仅适用于某些电子邮件提供商,可能是因为电子邮件提供商意识到即使地址是Yahoo,SMTP服务器也不会因此拒绝电子邮件。这只是一种预感,但它可能会解释它(如果不是这样的话,任何人都可以更容易地从“任何地址”发送电子邮件)。