Sending email from gmail using Python

╄→гoц情女王★ 提交于 2019-12-05 14:31:08

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!