我对python很陌生,当我试图使用python发送邮件时,我的程序如下所示
import smtplib
from smtplib import SMTP
sender = 'raju.ab@gmail.com'
receivers = ['sudeer.p@eunoia.in']
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中发送电子邮件请解释。
发布于 2014-12-03 13:40:13
我在代码中所做的:
1.添加一个错误对象以获取错误消息
import smtplib
from smtplib import SMTP
try:
sender = 'xxx@gmail.com'
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"如果你运行这段代码,你会看到这样一条错误信息,说明谷歌不允许你通过代码登录。
gmail中要改变的事情:
1.登录gmail
2.转到这个链接https://www.google.com/settings/security/lesssecureapps
3.单击“启用”,然后重试代码
希望能有所帮助:)
但是如果你启用它,就会有安全威胁。
发布于 2014-12-03 13:30:13
正如这里所说:How to send an email with Gmail as provider using Python?
这个密码起作用了。但GMAIL会警告你,如果你想让这个脚本发送电子邮件或不。在您的帐户中登录,并访问以下网址:https://www.google.com/settings/security/lesssecureapps
import smtplib
gmail_user = "yourmail@gmail.com"
gmail_pwd = "mypassword"
FROM = 'yourmail@gmail.com'
TO = ['receiber@email.com'] #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"https://stackoverflow.com/questions/27272367
复制相似问题