为什么Python标准库对发送邮件支持薄弱
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')])
有没有什么原因导致这不在“自带电池”的标准库里呢?
2 个回答
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()
2
我觉得这个问题其实是关于电子邮件消息结构的复杂性,而不是Python里的SMTP库有什么问题。
这个PHP的例子看起来也并没有比你的Python例子简单。