Question:In Python, how would I send an email with the contents of a text file? I have a text file named “example.txt” that contains some plain string data. I’m attempting to use Python to develop a code that will send those contents via email. I don’t want to attach the file; instead, I want to send the content as the email’s body. I would be grateful if someone could assist me with this problem.
Answer:I’m not sure which module you are using for smtp, but I found this tutorial called Sending Emails with Python by RealPython.com. Check it out if you are using smtplib.
To solve your issue of wanting to read the text file’s contents, instead of attaching a file, I wrote a script to read the contents of a textfile and put it into a list, which I proceeded to turn into one string (because smtplib wants a string for the email message and not a list):
In the tutorial I linked above, it says to send a plain text email by adding the following, to your script:
Lastly, My answer revolves around the tutorial but the script that reads the textfile can be used regardless of what module you use for sending emails.
If you have better answer, please add a comment about this, thank you!