我是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中发送电子邮件请解释
答案 0 :(得分:2)
如此处所说: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"
答案 1 :(得分:2)
我在代码中做了什么:
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.单击“启用”,然后重试代码
希望有所帮助:)
但如果你启用它就会有安全威胁