Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda