开发者

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.


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>%s</pre></body></html>" % 
             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)                
    session.quit()


I see you have a clue about what you did wrong.

In this case, the method attach() refers to adding something to the email. This is confusing because when we thing about attaching things and email, we think about adding extra files, not the body.

Based on some other examples, it seems that the attach method is used to add either text to the body or a file to the email.

So, to answer your question, the attach method does what you think it does and more--it also adds text to the body.

Welcome to SO, by the way. Smart choice picking Python for learning how to script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜