python怎么发gmail邮件:python模拟登录gmail并发送邮件

发布时间:2019-12-15编辑:脚本学堂
一个python发送gmail邮件的例子,在python中发送邮件并不困难,这里举的这个例子,使用python中smtp库实现gmail邮箱登录及发送邮件的功能。

python登录gmail并发送gmail邮件

在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 = "rn".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 + "rnrn" + body_of_email
session.sendmail(GMAIL_USERNAME, recipient, content)