如何使用Python发送电子邮件作为提供者?
我正尝试使用python发送电子邮件(Gmail),但是我收到以下错误消息。
Traceback (most recent call last): File "emailSend.py", line 14, in <module> server.login(username,password) File "/usr/lib/python2.5/smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by server.") smtplib.SMTPException: SMTP AUTH extension not supported by server.
Python脚本如下。
import smtplib fromaddr = 'user_me@gmail.com' toaddrs = 'user_you@gmail.com' msg = 'Why,Oh why!' username = 'user_me@gmail.com' password = 'pwd' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit()
在直接进入STARTTLS
之前,您需要说EHLO
:
server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls()
另外,你应该真的创buildFrom:
, To:
和Subject:
邮件标题,以空行分隔邮件正文,并使用CRLF
作为EOL标记。
例如
msg = "\r\n".join([ "From: user_me@gmail.com", "To: user_you@gmail.com", "Subject: Just a message", "", "Why, oh why" ])
def send_email(user, pwd, recipient, subject, body): import smtplib gmail_user = user gmail_pwd = pwd FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, message) server.close() print 'successfully sent the mail' except: print "failed to send mail"
如果你想使用Port 465,你必须创build一个SMTP_SSL
对象:
# SMTP_SSL Example server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465) server_ssl.ehlo() # optional, called by login() server_ssl.login(gmail_user, gmail_pwd) # ssl server doesn't support or need tls, so don't call server_ssl.starttls() server_ssl.sendmail(FROM, TO, message) #server_ssl.quit() server_ssl.close() print 'successfully sent the mail'
我遇到了类似的问题,偶然发现了这个问题。 我有一个SMTP身份validation错误,但我的用户名/密码是正确的。 这是什么修复它。 我读过这个:
https://support.google.com/accounts/answer/6010255
简而言之,谷歌不允许你通过smtpliblogin,因为它已经标记这种login为“不太安全”,所以你必须做的是当你login到你的谷歌帐户时去这个链接,并允许访问:
https://www.google.com/settings/security/lesssecureapps
一旦设置(见下面的截图),它应该工作。
login现在工作:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() smtpserver.login('me@gmail.com', 'me_pass')
更改后的响应:
(235, '2.7.0 Accepted')
事先回复:
smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')
还是行不通? 如果您仍然收到SMTPAuthenticationError,但现在的代码是534,因为该位置是未知的。 点击此链接:
https://accounts.google.com/DisplayUnlockCaptcha
点击继续,这应该让你10分钟注册你的新应用程序。 所以现在继续进行另一次login尝试,它应该工作。
更新 :这似乎并没有马上工作,你可能会卡住一段时间,在smptlib中得到这个错误:
235 == 'Authentication successful' 503 == 'Error: already authenticated'
该消息表示使用浏览器login:
SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')
启用'lesssecureapps'后,去喝咖啡,回来,再次尝试'DisplayUnlockCaptcha'链接。 根据用户体验,更改可能需要一个小时才能完成。然后再次尝试login过程。
你可以在这里find它: http : //jayrambhia.com/blog/send-emails-using-python
smtp_host = 'smtp.gmail.com' smtp_port = 587 server = smtplib.SMTP() server.connect(smtp_host,smtp_port) server.ehlo() server.starttls() server.login(user,passw) fromaddr = raw_input('Send mail by the name of: ') tolist = raw_input('To: ').split() sub = raw_input('Subject: ') msg = email.MIMEMultipart.MIMEMultipart() msg['From'] = fromaddr msg['To'] = email.Utils.COMMASPACE.join(tolist) msg['Subject'] = sub msg.attach(MIMEText(raw_input('Body: '))) msg.attach(MIMEText('\nsent via python', 'plain')) server.sendmail(user,tolist,msg.as_string())
不直接相关,但仍值得指出的是,我的软件包试图使发送Gmail邮件真正快速和无痛。 它还试图维护一个错误列表,并尝试立即指出解决scheme。
这实际上只需要这个代码来完成你写的东西:
import yagmail yag = yagmail.SMTP('user_me@gmail.com') yag.send('user_you@gmail.com', 'Why,Oh why!')
或者一个class轮:
yagmail.SMTP('user_me@gmail.com').send('user_you@gmail.com', 'Why,Oh why!')
对于软件包/安装,请查看git或pip ,可用于Python 2和Python 3。
你失望了OOP?
#!/usr/bin/env python import smtplib class Gmail(object): def __init__(self, email, password): self.email = email self.password = password self.server = 'smtp.gmail.com' self.port = 587 session = smtplib.SMTP(self.server, self.port) session.ehlo() session.starttls() session.ehlo session.login(self.email, self.password) self.session = session def send_message(self, subject, body): ''' This must be removed ''' headers = [ "From: " + self.email, "Subject: " + subject, "To: " + self.email, "MIME-Version: 1.0", "Content-Type: text/html"] headers = "\r\n".join(headers) self.session.sendmail( self.email, self.email, headers + "\r\n\r\n" + body) gm = Gmail('Your Email', 'Password') gm.send_message('Subject', 'Message')
似乎是老smtplib
问题。 在python2.7
一切工作正常。
更新 :是的, server.ehlo()
也可以帮助。
现在有一个gmail API,它可以让你发送电子邮件,阅读电子邮件,并通过REST创build草稿。 与SMTP调用不同,它是非阻塞的,这对于基于线程的web服务器在请求线程中发送电子邮件(例如python webservers)可能是件好事。 该API也相当强大。
- 当然,电子邮件应该交给一个非web服务器队列,但很高兴有select。
如果您在域上拥有Google Appspipe理员权限,则最容易设置,因为这样您就可以为您的客户提供一揽子许可。 否则,你不得不摆弄OAuthauthentication和许可。
这是一个展示它的要点:
来自@David的伟大答案,这里是Python 3没有通用的尝试 – 除了:
def send_email(user, password, recipient, subject, body): gmail_user = user gmail_pwd = password FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, message) server.close()
import smtplib fromadd='from@gmail.com' toadd='send@gmail.com' msg='''hi,how r u''' username='abc@gmail.com' passwd='password' try: server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username,passwd) server.sendmail(fromadd,toadd,msg) print("Mail Send Successfully") server.quit() except: print("Error:unable to send mail") NOTE:https://www.google.com/settings/security/lesssecureapps that should be enabled
import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login("fromaddress", "password") msg = "HI!" server.sendmail("fromaddress", "receiveraddress", msg) server.quit()