SeanK137 SeanK137 - 1 year ago 94
Python Question

Sending email from gmail using Python

I'm trying to teaching myself how to program by building programs/scrips that will be useful to me. I'm trying to retool a script I found online to send an email through gmail using a python script (Source).

This example has a portion of code to attach files, which I don't want/need. I have tweaked the code so that I don't have to attach any files, but when I do this I lose the body of the email. Any help/tips on how to modify the code to keep the body of the email intact?

Appreciate the help.

Answer Source

The sample code you're using creates a multi-part MIME message. Everything is an attachment, including the message body. If you just want to send a plain old single-part plain text or HTML message, you don't need any of the MIME stuff. It just adds complexity. See that bit in your sample's sendmail() call where it says msg.as_string()? Well, that just converts the MIME objects you've created to text. It's easy enough to specify the text yourself, if you are dealing with text to start with.

The function below is similar to code I used for mailing a log file in a script I wrote. It takes a plain text body and converts it to preformatted HTML (to work better in Outlook). If you want to keep it plain text, just take out the line that adds the HTML tags, and change the Content-Type header to "text/plain."

import smtplib

def sendmail(sender, recipient, subject, body, server="localhost"):
    "Sends an e-mail to the specified recipient."

    body = ("<html><head></head><body><pre>" + 
             body.replace("&", "&amp;").replace("<", "&lt;") + 

    headers = ["From: " + sender,
               "Subject: " + subject,
               "To: " + recipient,
               "MIME-Version: 1.0",
               "Content-Type: text/html"]
    headers = "\r\n".join(headers)

    session = smtplib.SMTP(server)
    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)                
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download