• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: Sending an email of the contents inside a text file

Resolved: Sending an email of the contents inside a text file

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

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):
If you want to keep it as a list, just erase the line with email_body.
In the tutorial I linked above, it says to send a plain text email by adding the following, to your script:
So we would just replace message with our email_body string:
Side Note: the tutorial mentions using 2 new line characters for the email subject. That’s important to keep in mind if you want to include an email subject in your text file. See the link above for details.
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!

email file python smtp
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Why when i change manualy the url on my react page it ignores the .css file?

24/03/2023

Resolved: navigate and redirect not redirecting to path in react router

24/03/2023

Resolved: Time Complexity: Find the number of people who know a secret leetcode 2327

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.