简体   繁体   English

Python:附加MIME编码的文本文件

[英]Python: Attaching MIME encoded text file

After a bunch of fiddling, I finally hit upon the magical sequence to attach a text file to an email (many thanks to previous posts on this service). 经过一番摆弄之后,我终于找到了神奇的步骤,将文本文件附加到电子邮件中(这要感谢以前在此服务上的帖子)。

I'm left wondering what the lines: 我只想知道行是什么:

attachment.add_header('Content-Disposition'. . .)

--and-- - 和 -

e_msg = MIMEMultipart('alternative')

actually do. 确实可以。

Can someone unsilence the Mimes for me please (sorry couldn't resist) 有人可以帮我沉默哑剧吗(抱歉无法抗拒)

import smtplib
from email import Encoders
from email.message import Message
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

smtp_server = "1.2.3.4"
smtp_login = "account"
smpt_password = "password"

server = smtplib.SMTP(smtp_server)
server.login(smtp_login,smtp_password)

f = file("filename.csv")
attachment = MIMEText(f.read())
attachment.add_header('Content-Disposition', 'attachment', filename="filename.csv")
e_msg = MIMEMultipart('alternative')
e_msg.attach(attachment)
e_msg['Subject'] = 'Domestic Toll Monitor'
e_msg['From'] = smtp_account
body = 'Some nifty text goes here'
content = MIMEText(body)
e_msg.attach(content)
server.sendmail(smtp_from, smtp_to, e_msg.as_string())

Basically, MIME is the specification defining email structure. 基本上,MIME是定义电子邮件结构的规范。 The Multipart structure is designed to allow for multiple types of messages and attachments to be sent within the same message. Multipart结构旨在允许在同一条消息中发送多种类型的消息和附件。 For example, an email might have a plain text version for backwards compatibility and a rich text or html formatted message for modern clients. 例如,电子邮件可能具有用于向后兼容的纯文本版本,而对于现代客户端则具有富文本或html格式的消息。 Attachments count as a "part", and thus require their own header. 附件算作“部分”,因此需要它们自己的标题。 In this case, you're adding a "Content-Disposition" type header for the attachment. 在这种情况下,您将为附件添加“ Content-Disposition”类型的标题。 If you're really interested in what that means, you can read the specification here . 如果您真的对这意味着什么感兴趣,可以在此处阅读规范。 As for the "Alternative portion, you're setting the message to multipart and defining the types of parts that you have attached and how the client needs to handle them. There are some standard presets defining various scenarios, but Alternative is something of a wildcard, used when there is a part whose type might not be recognized or handled by most clients. For the record, I believe you also could have used a "Mixed" type. The nice thing about MIME is that while it is complicated, its thoroughly defined and its very easy to look up the specification. 至于“替代部分,您将消息设置为多部分,并定义了已附加的部分的类型以及客户需要如何处理它们。有一些标准的预设定义了各种情况,但是替代则是通配符,当某些部分的类型可能无法为大多数客户识别或处理时使用。为了便于记录,我相信您也可以使用“混合”类型。MIME的优点是,尽管它很复杂,但它却可以定义,并且非常容易查找规格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM