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 raiseSMTPException("SMTP AUTH extension not supported by server.")
smtplib.SMTPException: SMTP AUTH extension not supported by server.
I am trying to send email (Gmail) using python, but I am getting following error.
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.
You need to say EHLO before just running straight into STARTTLS:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
Also you should really create From:, To: and Subject: message headers, separated from the message body by a blank line and use CRLF as EOL markers.
E.g.
msg = "\r\n".join([
"From: user_me@gmail.com",
"To: user_you@gmail.com",
"Subject: Just a message",
"",
"Why, oh why"
])
回答 1
def send_email(user, pwd, recipient, subject, body):import smtplib
FROM = user
TO = recipient if isinstance(recipient, 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(user, pwd)
server.sendmail(FROM, TO, message)
server.close()print'successfully sent the mail'except:print"failed to send mail"
如果要使用端口465,则必须创建一个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'
def send_email(user, pwd, recipient, subject, body):
import smtplib
FROM = user
TO = recipient if isinstance(recipient, 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(user, pwd)
server.sendmail(FROM, TO, message)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
if you want to use Port 465 you have to create an SMTP_SSL object:
# 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'
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,'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')
I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:
In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as “less secure”, so what you have to do is go to this link while you’re logged in to your google account, and allow the access:
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')
Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:
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')
After enabling ‘lesssecureapps’, go for a coffee, come back, and try the ‘DisplayUnlockCaptcha’ link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.
#!/usr/bin/env python3# -*- coding: utf-8 -*-# =============================================================================# Created By : Jeromie Kirchoff# Created Date: Mon Aug 02 17:46:00 PDT 2018# =============================================================================# Imports# =============================================================================import smtplib
# =============================================================================# SET EMAIL LOGIN REQUIREMENTS# =============================================================================
gmail_user ='THEFROM@gmail.com'
gmail_app_password ='YOUR-GOOGLE-APPLICATION-PASSWORD!!!!'# =============================================================================# SET THE INFO ABOUT THE SAID EMAIL# =============================================================================
sent_from = gmail_user
sent_to =['THE-TO@gmail.com','THE-TO@gmail.com']
sent_subject ="Where are all my Robot Women at?"
sent_body =("Hey, what's up? friend!\n\n""I hope you have been well!\n""\n""Cheers,\n""Jay\n")
email_text ="""\
From: %s
To: %s
Subject: %s
%s
"""%(sent_from,", ".join(sent_to), sent_subject, sent_body)# =============================================================================# SEND EMAIL OR DIE TRYING!!!# Details: http://www.samlogic.net/articles/smtp-commands-reference.htm# =============================================================================try:
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.login(gmail_user, gmail_app_password)
server.sendmail(sent_from, sent_to, email_text)
server.close()print('Email sent!')exceptExceptionas exception:print("Error: %s!\n\n"% exception)
This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access.
Not directly related but still worth pointing out is that my package tries to make sending gmail messages really quick and painless. It also tries to maintain a list of errors and tries to point to the solution immediately.
It would literally only need this code to do exactly what you wrote:
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow importInstalledAppFlowfrom google.auth.transport.requests importRequestfrom email.mime.text importMIMETextimport base64
#pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib# If modifying these scopes, delete the file token.pickle.
SCOPES =['https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.send']def create_message(sender, to, subject, msg):
message =MIMEText(msg)
message['to']= to
message['from']= sender
message['subject']= subject
# Base 64 encode
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()return{'raw': b64_string}#return {'raw': base64.urlsafe_b64encode(message.as_string())}def send_message(service, user_id, message):#try:
message =(service.users().messages().send(userId=user_id, body=message).execute())print('Message Id: %s'% message['id'])return message
#except errors.HttpError, error:print( 'An error occurred: %s' % error )def main():"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds =None# The file token.pickle stores the user's access and refresh tokens, and is# created automatically when the authorization flow completes for the first# time.if os.path.exists('token.pickle'):with open('token.pickle','rb')as token:
creds = pickle.load(token)# If there are no (valid) credentials available, let the user log in.ifnot creds ornot creds.valid:if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())else:
flow =InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)# Save the credentials for the next runwith open('token.pickle','wb')as token:
pickle.dump(creds, token)
service = build('gmail','v1', credentials=creds)# Example read operation
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels',[])ifnot labels:print('No labels found.')else:print('Labels:')for label in labels:print(label['name'])# Example write
msg = create_message("from@gmail.com","to@gmail.com","Subject","Msg")
send_message( service,'me', msg)if __name__ =='__main__':
main()
You’ll need create a project with Google’s API interfaces through their website. Next you’ll need to enable the GMAIL API for your app. Create credentials and then download those creds, save it as credentials.json.
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
import base64
#pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send']
def create_message(sender, to, subject, msg):
message = MIMEText(msg)
message['to'] = to
message['from'] = sender
message['subject'] = subject
# Base 64 encode
b64_bytes = base64.urlsafe_b64encode(message.as_bytes())
b64_string = b64_bytes.decode()
return {'raw': b64_string}
#return {'raw': base64.urlsafe_b64encode(message.as_string())}
def send_message(service, user_id, message):
#try:
message = (service.users().messages().send(userId=user_id, body=message).execute())
print( 'Message Id: %s' % message['id'] )
return message
#except errors.HttpError, error:print( 'An error occurred: %s' % error )
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
# Example read operation
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])
# Example write
msg = create_message("from@gmail.com", "to@gmail.com", "Subject", "Msg")
send_message( service, 'me', msg)
if __name__ == '__main__':
main()
There is a gmail API now, which lets you send email, read email and create drafts via REST.
Unlike the SMTP calls, it is non-blocking which can be a good thing for thread-based webservers sending email in the request thread (like python webservers). The API is also quite powerful.
Of course, email should be handed off to a non-webserver queue, but it’s nice to have options.
It’s easiest to setup if you have Google Apps administrator rights on the domain, because then you can give blanket permission to your client. Otherwise you have to fiddle with OAuth authentication and permission.
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()
great answer from @David, here is for Python 3 without the generic try-except:
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()
Seems like problem of the old smtplib. In python2.7 everything works fine.
Update: Yep, server.ehlo() also could help.
回答 12
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