7

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.

baduker
  • 12,203
  • 9
  • 22
  • 39
user3558939
  • 105
  • 6
  • 2
    you'd like to send `test.txt` out as one attachment of one email? or put the content of `test.txt` into email body? – Sphinx Mar 08 '18 at 19:53
  • I'd like to send test.txt as the attachment of the email – user3558939 Mar 08 '18 at 19:59
  • I wonder if [StringIO](https://docs.python.org/3/library/io.html#io.StringIO) would be useful here? It's conventionally used for constructing a file-like object without actually creating a file. No idea whether smtplib would accept such a thing though. – Kevin Mar 08 '18 at 20:01
  • 1
    Follow https://stackoverflow.com/questions/3362600/how-to-send-email-attachments#3363254 - the `MimeApplication` method doesn't need a file - just its contents and a name to create an attachment from. – match Mar 08 '18 at 20:15
  • But how would I write text into the file though? – user3558939 Mar 09 '18 at 15:51
  • Why do you want to pollute the file system? Either you already have a file and you want to attach it, or you have a buffer in memory and want to attach that. Saving the buffer in a file is useless and complicates your question needlessly. – tripleee Mar 12 '18 at 19:05

1 Answers1

1

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)
stacksonstacks
  • 5,950
  • 3
  • 23
  • 39
  • I'm able to send a document, but the text file is blank. Also for some reason, it sends two text files as attachments. Not too sure why. f = StringIO() f.write(u'hi') msg1 = MIMEBase('application', "octet-stream") msg1.set_payload(f.read()) #encoders.encode_base64(msg) msg1.add_header('Content-Disposition', 'attachment', filename='test.txt') msg.attach(msg1) – user3558939 Mar 12 '18 at 14:27
  • Got it - it should be msg.set_payload(f.getvalue()) – user3558939 Mar 12 '18 at 17:24