0

Python 被宣传为“包含电池”的语言。所以,我想知道为什么它的标准库不包括对电子邮件的高级支持:

我发现您需要对 MIME 有很多了解才能创建与您在典型电子邮件客户端中可以实现的功能等效的电子邮件,例如处理 HTML 内容、嵌入的图像和文件附件。

为此,您需要对消息进行低级组装,例如:

  • 处理MIMEMultipart部分,并了解related,alternate等。
  • 了解文件编码,例如base64

如果您刚刚了解 MIME 足以组装这样的电子邮件,则很容易陷入陷阱,例如错误的部分嵌套,并创建一些电子邮件客户端可能无法正确查看的消息。

我不需要了解 MIME 就能正确发送电子邮件。高级库支持应该封装所有这些 MIME 逻辑,允许您编写如下内容:

m = Email("mailserver.mydomain.com")
m.setFrom("Test User <test@mydomain.com>")
m.addRecipient("you@yourdomain.com")
m.setSubject("Hello there!")
m.setHtmlBody("The following should be <b>bold</b>")
m.addAttachment("/home/user/image.png")
m.send()

非标准库解决方案是pyzmail

import pyzmail
sender=(u'Me', 'me@foo.com')
recipients=[(u'Him', 'him@bar.com'), 'just@me.com']
subject=u'the subject'
text_content=u'Bonjour aux Fran\xe7ais'
prefered_encoding='iso-8859-1'
text_encoding='iso-8859-1'
pyzmail.compose_mail(
        sender,  recipients, 
        subject, prefered_encoding,  (text_content, text_encoding), 
        html=None, 
        attachments=[('attached content', 'text', 'plain', 'text.txt',
                      'us-ascii')])

是否有任何理由不在“包含电池”标准库中?

4

2 回答 2

2

我认为问题更多是关于电子邮件结构的复杂性,而不是 Python 中 smpt 库的弱点。

PHP 中的这个示例似乎并不比您的 Python 示例简单。

于 2013-01-30T09:06:01.157 回答
1
import smtplib
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail("me@somewhere.com", ["you@elsewhere.com"],
    """Subject: This is a message sent with very little configuration.

    It will assume that the mailserver is on localhost on the default port
    (25) and also assume a message type of text/plain.

    Of course, if you want more complex message types and/or server
    configuration, it kind of stands to reason that you'd need to do
    more complex message assembly. Email (especially with embedded content)
    is actually a rather complex area with many possible options.
    """
smtp.quit()
于 2013-01-30T08:50:29.243 回答