Search code examples
pythonemailtext

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.


Solution

  • 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)