Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report

0

I found this post while figuring out how to do this with the newer EmailMessage, which was introduced in Python 3.6 (see https://docs.python.org/3/library/email.message.html). It's slightly less code:

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!