[英]Trying to send email from python
我是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中發送電子郵件,請解釋
如此處所述: 如何使用Python以提供者身份通過Gmail發送電子郵件?
此代碼有效。 但是GMAIL會警告您是否要允許此腳本發送電子郵件。 登錄您的帳戶,然后訪問以下URL: 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,添加了一個錯誤對象以獲取錯誤信息
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"
如果您運行此代碼,您會看到一條錯誤消息,指出Google不允許您通過代碼登錄
gmail發生的變化:
1.登錄gmail
2.轉到此鏈接https://www.google.com/settings/security/lesssecureapps
3.單擊啟用,然后重試代碼
希望對您有所幫助:)
但是,如果您啟用它,則會存在安全威脅
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.