简体   繁体   English

使用Python发送电子邮件

[英]Sending an email using Python

I'm trying to send myself an email using Python's smtplib module. 我正在尝试使用Python的smtplib模块向自己发送电子邮件。 Here's the code I'm trying to execute: 这是我要执行的代码:

import smtplib

sender = 'manas.oid@gmail.com'
receivers = ['manas.oid@gmail.com']

message = """From: From Person <manas.oid@gmail.com>
To: To Person <manas.oid@gmail.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""
try:
   smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except smtplib.SMTPException:
   print "Error: unable to send email"

However, I get a 'Error:unable to send email' message when I try to execute this script. 但是,当我尝试执行此脚本时,出现“错误:无法发送电子邮件”消息。 What seems to be wrong with my script? 我的脚本似乎出了什么问题?

您没有登录,也没有使用smtpObj.starttls()启动连接。

To add on to what @Malik says, below are the steps you need to perform before you'll be able to do anything with GMail ( provided less secure apps can access your account, see below ). 为了补充@Malik所说的内容,以下是您必须执行的步骤,才能使用GMail进行任何操作( 如果安全性较低的应用程序可以访问您的帐户,请参见下文 )。

conn = SMTP('smtp.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.login(username,pwd)
conn.sendmail(username, emailID, message)

Note that after recent changes to GMail, you'll need to explicitly allow less secure apps to access your account. 请注意,在最近对GMail进行更改之后,您需要明确允许安全性较低的应用访问您的帐户。 GMail would block your request to login until you enable it. GMail将阻止您的登录请求,直到您启用它为止。 Link to enable less secure apps to access: https://support.google.com/accounts/answer/6010255?hl=en 链接以启用安全性较低的应用程序进行访问: https : //support.google.com/accounts/answer/6010255?hl=zh_CN

Gmail wouldn't let you send an unauthenticated email from an account. Gmail不允许您通过帐户发送未经身份验证的电子邮件。 Instead, use the Gmail API to send emails. 而是使用Gmail API发送电子邮件。 Some useful links below: 以下是一些有用的链接:

Authentication: https://developers.google.com/gmail/api/auth/web-server 身份验证: https//developers.google.com/gmail/api/auth/web-server
Email: https://developers.google.com/gmail/api/guides/sending 电子邮件: https//developers.google.com/gmail/api/guides/sending

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM