【问题标题】:Create a text file, and email it without saving it locally创建一个文本文件,并通过电子邮件发送而不在本地保存
【发布时间】:2018-03-08 19:51:43
【问题描述】:

我想在 Python 中创建一个文本文件,向其中写入一些内容,然后通过电子邮件将其发送出去(将 test.txt 作为电子邮件附件)。

但是,我无法在本地保存此文件。有谁知道该怎么做?

只要我打开要写入的文本文件,它就会本地保存在我的计算机上。

f = open("test.txt","w+")

我正在使用smtplibMIMEMultipart 发送邮件。

【问题讨论】:

  • 您想将test.txt 作为一封电子邮件的附件发送出去吗?还是将test.txt的内容放入邮件正文?
  • 我想将 test.txt 作为电子邮件的附件发送
  • 我想知道StringIO在这里是否有用?它通常用于构建类似文件的对象,而无需实际创建文件。不知道 smtplib 是否会接受这样的事情。
  • Follow stackoverflow.com/questions/3362600/… - MimeApplication 方法不需要文件 - 只需要其内容和用于创建附件的名称。
  • 但是我如何将文本写入文件呢?

标签: python email text


【解决方案1】:

StringIO 是要走的路……

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

from io import StringIO

email = MIMEMultipart()
email['Subject'] = 'subject'
email['To'] = 'recipient@example.com'
email['From'] = 'sender@example.com'

# Add the attachment to the message
f = StringIO()
# write some content to 'f'
f.write("content for 'test.txt'")
f.seek(0)

msg = MIMEBase('application', "octet-stream")
msg.set_payload(f.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition',
               'attachment',
               filename='test.txt')
email.attach(msg)

【讨论】:

  • 我可以发送文档,但文本文件为空白。同样出于某种原因,它会发送两个文本文件作为附件。不太清楚为什么。 f = StringIO() f.write(u'hi') msg​​1 = MIMEBase('application', "octet-stream") msg​​1.set_payload(f.read()) #encoders.encode_base64(msg) msg​​1.add_header(' Content-Disposition', 'attachment', filename='test.txt') msg​​.attach(msg1)
  • 知道了——应该是 msg.set_payload(f.getvalue())
【解决方案2】:

我在研究如何使用 Python 3.6 中引入的较新的 EmailMessage 时发现了这篇文章(参见 https://docs.python.org/3/library/email.message.html)。代码略少:

from email.message import EmailMessage
from io import StringIO
from smtplib import SMTP

message = EmailMessage()
message['Subject'] = 'Subject'
message['From'] = 'from@example.com'
message['To'] = 'to@example.com'

f = StringIO()
f.name = 'attachment.txt'
f.write('contents of file')
f.seek(0)
message.add_attachment(f.read(), filename=f.name)
with SMTP('yourmailserver.com', 25) as server:
    server.send_message(message)

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2012-11-11
    • 2011-08-20
    相关资源
    最近更新 更多