如何使用 SMTP 发送附件?
我想编写一个使用 Python 的 smtplib 发送电子邮件的程序。我搜索了文档和 RFC,但找不到任何与附件相关的内容。因此,我确信我错过了一些更高层次的概念。有人可以告诉我附件在 SMTP 中是如何工作的吗?
I want to write a program that sends email using Python's smtplib. I searched through the document and the RFCs, but couldn't find anything related to attachments. Thus, I'm sure there's some higher-level concept I'm missing out on. Can someone clue me in on how attachments work in SMTP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是我从我们所做的工作申请中截取的一个示例。它创建带有 Excel 附件的 HTML 电子邮件。
Here's an example I snipped out of a work application we did. It creates an HTML email with an Excel attachment.
您要检查的是
email
模块。它可以让您构建 MIME 兼容的消息,然后使用 smtplib 发送。What you want to check out is the
email
module. It lets you build MIME-compliant messages that you then send with smtplib.嗯,附件不以任何特殊方式处理,它们“只是”消息对象树的叶子。您可以在此部分中找到有关符合 MIME 的消息的任何问题的答案关于 email python 包的文档。
一般来说,任何类型的附件(读取:原始二进制数据)都可以使用 base64 表示
(或类似)
Content-Transfer-Encoding
。Well, attachments are not treated in any special ways, they are "just" leaves of the Message-object tree. You can find the answers to any questions regarding MIME-compliant mesasges in this section of the documentation on the email python package.
In general, any kind of attachment (read: raw binary data) can be represented by using base64
(or similar)
Content-Transfer-Encoding
.以下是如何发送带有 zip 文件附件和 utf-8 编码的主题+正文的电子邮件。
由于缺乏针对这一特定案例的文档和样本,要弄清楚这一点并不容易。
回复中的非 ASCII 字符需要使用 ISO-8859-1 等进行编码。可能存在一个可以做到这一点的函数。
提示:
给自己发送一封电子邮件,保存并检查内容以了解如何在 Python 中执行相同的操作。
这是 Python 3 的代码:
Here's how to send e-mails with zip file attachments and utf-8 encoded subject+body.
It was not straightforward to figure this one out, due to lack of documentation and samples for this particular case.
Non-ascii characters in replyto needs to be encoded with, for instance, ISO-8859-1. There probably exists a function that can do this.
Tip:
Send yourself an e-mail, save it and examine the content to figure out how to do the same thing in Python.
Here's the code, for Python 3:
以下是包含 PDF 附件、文本“正文”并通过 Gmail 发送的邮件示例。
Here is an example of a message with a PDF attachment, a text "body" and sending via Gmail.