Home > database >  Sending an email of the contents inside a text file
Sending an email of the contents inside a text file

Time:06-16

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.

CodePudding user response:

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

with open(“example.txt”, “r”) as textfile:
    content = textfile.readlines()
    email_body = “”.join(content) # new line characters will be included
    textfile.close()

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:


sender_email = "[email protected]"
receiver_email = "[email protected]"
message = """\
Subject: Hi there

This message is sent from Python."""

server.sendmail(sender_email, receiver_email, message)

So we would just replace message with our email_body string:


sender_email = "[email protected]"
receiver_email = "[email protected]"
# remove message and replace it with email_body
server.sendmail(sender_email, receiver_email, email_body)

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.

  • Related