使用Python从Gmail发送电子邮件

编程入门 行业动态 更新时间:2024-10-27 16:27:19
本文介绍了使用Python从Gmail发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图通过构建对我有用的程序/脚本来教自己如何编程。我正在尝试将我在线上找到的脚本重新制作成通过gmail使用python脚本发送电子邮件( Source )。

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?

欣赏帮助。

推荐答案

您使用的示例代码创建了多部分MIME消息。一切都是附件,包括邮件正文。如果您只想发送普通的单部分纯文本或HTML邮件,则不需要任何MIME内容。这只会增加复杂性。在你的示例的sendmail()调用中看到msg.as_string()的那一点?那么,这只是将您创建的MIME对象转换为文本。如果你正在处理文本开头,很容易就可以自己指定文本。

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.

下面的函数类似于我用于邮寄日志文件的代码我写的脚本。它采用纯文本正文并将其转换为预格式化的HTML(以在Outlook中更好地工作)。如果你想保持纯文本,只需取出添加HTML标签的行,然后将Content-Type标题更改为text / plain。

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

更多推荐

使用Python从Gmail发送电子邮件

本文发布于:2023-10-07 10:24:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469133.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送电子邮件   Python   Gmail

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!