2014-12-03 168 views
0

我是新来的蟒蛇,当我试图发送邮件发送电子邮件通过使用python我的计划是波纹管试图从蟒蛇

import smtplib 
from smtplib import SMTP 

sender = '[email protected]' 
receivers = ['[email protected]'] 

message = """ this message sending from python 
for testing purpose 
""" 

try: 
smtpObj = smtplib.SMTP('smtp.gmail.com', 587) 
smtpObj.ehlo() 
smtpObj.starttls() 
smtpObj.ehlo() 
smtpObj.login(username,password) 
smtpObj.sendmail(sender, receivers, message) 
smtpObj.quit() 
print "Successfully sent email" 
except smtplib.SMTPException: 

打印“错误:无法发送电子邮件”

当我执行它显示错误:无法发送邮件,如何在python发送电子邮件请解释

+1

*“它显示错误:无法发送邮件信息”* - 这正是你要求它做的!如果你没有用'try'包装整个过程,你会得到一个更具体的错误信息,给你更多关于这个问题的信息。 – jonrsharpe 2014-12-03 13:01:10

回答

1

我已经在代码中完成跑这个代码你会看到这样的错误消息,说明谷歌不允许你通过代码登录

在Gmail中改变的事情:

1.登陆到Gmail

2.进入这个链接https://www.google.com/settings/security/lesssecureapps

3.Click使然后重试代码

希望它能帮助:)

但也有,如果安全威胁ü启用它

+0

我在except行得到无效的语法,指向错误之前的逗号(代码中的第20行)。为什么? – 2016-12-13 00:19:08

+0

@YannisDran你使用的是python 3 – The6thSense 2016-12-15 06:25:57

+0

是的,我已经在打印后放了括号。 – 2016-12-15 07:58:41

2

因为在这里说:How to send an email with Gmail as provider using Python?

此代码的工作。但是,如果您想允许此脚本发送电子邮件,GMAIL会警告您。登录您的帐户,并accesss这个网址:

1.添加一个错误对象来获得错误信息

import smtplib 
from smtplib import SMTP  

try: 
    sender = '[email protected]' 
    receivers = ['xxx.com'] 

    message = """ this message sending from python 
    for testing purpose 
    """ 
    smtpObj = smtplib.SMTP(host='smtp.gmail.com', port=587) 
    smtpObj.ehlo() 
    smtpObj.starttls() 
    smtpObj.ehlo() 
    smtpObj.login('xxx','xxx') 
    smtpObj.sendmail(sender, receivers, message) 
    smtpObj.quit() 
    print "Successfully sent email" 
except smtplib.SMTPException,error: 
    print str(error) 
    print "Error: unable to send email" 

如果妳:https://www.google.com/settings/security/lesssecureapps

import smtplib 
gmail_user = "[email protected]" 
gmail_pwd = "mypassword" 
FROM = '[email protected]' 
TO = ['[email protected]'] #must be a list 
SUBJECT = "Testing sending using gmail" 
TEXT = "Testing sending mail using gmail servers" 
# Prepare actual message 
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s 
""" % (FROM, ", ".join(TO), SUBJECT, TEXT) 
try: 
    #server = smtplib.SMTP(SERVER) 
    server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work! 
    server.ehlo() 
    server.starttls() 
    server.login(gmail_user, gmail_pwd) 
    server.sendmail(FROM, TO, message) 
    #server.quit() 
    server.close() 
    print 'successfully sent the mail' 
except: 
    print "failed to send mail" 
+0

感谢有关警告的信息。 URL信息适用于我。 – BaldDude 2014-12-04 13:20:40