Home  >  Article  >  Backend Development  >  用Python登录Gmail并发送Gmail邮件的教程

用Python登录Gmail并发送Gmail邮件的教程

WBOY
WBOYOriginal
2016-06-10 15:14:521798browse

 这篇快文介绍了使用Gmail作为您的e-mail服务器,通过Python的内置SMTP库发送电子邮件。它并不复杂,我保证。

下面是如何在Python中登录GMail:
 

import smtplib
 
# The below code never changes, though obviously those variables need values.
session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login(GMAIL_USERNAME, GMAIL_PASSWORD)

下面是如何在Python中发送邮件:
 

headers = "\r\n".join(["from: " + GMAIL_USERNAME,
            "subject: " + email_subject
            "to: " + recipient,
            "mime-version: 1.0",
            "content-type: text/html"])
 
# body_of_email can be plaintext or html!          
content = headers + "\r\n\r\n" + body_of_email
session.sendmail(GMAIL_USERNAME, recipient, content)

取决于您对Python的掌握,这可能是一段相当小或相当长的代码。


对我来说,第一次拿一个程序来发送电子邮件,就如我看到黑客帝国里面的场景那一刻,就像我第一次在 Godaddy 上建立一个网站,或者像我第一次使用 JOptionPane 的疑惑。这是一个实现方法(一个简单的方法,它使得实现类似的应用变得非常简单),虽然我以前看过很多发邮件的代码,但这仍然给我留下了深刻的印象。


另外,尽管上面的代码简单,但我第一次也是倾尽全力,花了两个多小时才把那些代码写出来。因此我希望能帮到一些其他人。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn