Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a text file, and email it without saving it locally

Tags:

python

text

email

I would like to create a text file in Python, write something to it, and then e-mail it out (put test.txt as an email attachment).

However, I cannot save this file locally. Does anyone know how to go about doing this?

As soon as I open the text file to write in, it is saved locally on my computer.

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

I am using smtplib and MIMEMultipart to send the mail.

like image 509
user3558939 Avatar asked Mar 08 '18 19:03

user3558939


1 Answers

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'] = '[email protected]'
email['From'] = '[email protected]'

# 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)
like image 99
stacksonstacks Avatar answered Sep 22 '22 06:09

stacksonstacks