我想在Python中创建一个文本文件,写一些东西,然后通过电子邮件发送(test.txt作为电子邮件附件).
但是,我无法在本地保存此文件.有谁知道怎么做这个?
只要我打开要写入的文本文件,它就会在我的计算机上本地保存.
f = open("test.txt","w+")
Run Code Online (Sandbox Code Playgroud)
我正在使用smtplib并MIMEMultipart发送邮件.
StringIO is the way to go...
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
790 次 |
| 最近记录: |