Setup:
Users are created on On-Prem AD and synced to Azure AD via Azure AD Connect
I have a single-tenant app set up on Azure AD
I created a user (On-Prem, synced to AAD) that can authenticate without MFA (we need to use username-password authentication due to an internal limitation).
Here is the non-interactive authentication code:
import msal
# create a public client app
authority_url = f"https://login.microsoftonline.com/{TENANT_ID}"
msal_app = msal.PublicClientApplication(client_id=CLIENT_ID, authority=authority_url)
# acquire token
token = msal_app.acquire_token_by_username_password(username=USERNAME, password=PASSWORD, scopes=SCOPES)
I'm getting the following error:
Traceback (most recent call last):
File "/./scripts/aad.py", line 8, in <module>
token = msal_app.acquire_token_by_username_password(
File "/usr/local/lib/python3.10/site-packages/msal/application.py", line 1420, in acquire_token_by_username_password
response = _clean_up(self._acquire_token_by_username_password_federated(
File "/usr/local/lib/python3.10/site-packages/msal/application.py", line 1447, in _acquire_token_by_username_password_federated
wstrust_result = wst_send_request(
File "/usr/local/lib/python3.10/site-packages/msal/wstrust_request.py", line 60, in send_request
return parse_response(resp.text)
File "/usr/local/lib/python3.10/site-packages/msal/wstrust_response.py", line 49, in parse_response
raise RuntimeError("WsTrust server returned error in RSTR: %s" % (error or body))
RuntimeError: WsTrust server returned error in RSTR: {'reason': 'MSIS7068: Access denied.', 'code': 'a:FailedAuthentication'}
Searching through Google I found that this can be caused by MFA, but the user is excluded from MFA. I've also verified that there are no Conditional Access policies in place to block the user accessing the app.
Using Interactive auth works as expected. Any ideas on how to get non-interactive auth to work or what might be the issue here?
First, no guesswork! You would need to login to Azure AD with elevated privilege (Security Reader at the least if not Global Administrator).
Go to Enterprise Applications and locate your application by client id.
One you are at the application, go to Sign-in tab/pane.
Review the sign-in activities. You should see the reason authentication failed in overview tab. Look at the Conditional Access tab and you will know if there is any policy that blocked the sign-in.
Take action based on what you identified in sign-in activity.
Okay, I am going to make an educated guess! When you login as non-interactive, you have two authentication choices - ROPC and Client Credential- both requires client_secret to be passed in the request but you have not! Since you are using username and password, it implies that msal is using ROPC and you must include client secret.
I see many solutions but still, I have a problem for send mail and I also set email and password to
~/.bash_profile so please help me.
Here my connfig.py file code
import os
class Config:
SECRET_KEY=os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI')
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 465
MAIL_USE_SSL= True
MAIL_USERNAME=os.environ.get('EMAIL_USER')
MAIL_PASSWORD=os.environ.get('EMAIL_PASS')
I also try the google two-step verification and app password still I have a problem. What can I do now?
I had the same problem when I debugged my code I found that my os.environ.get('EMAIL_USER') was empty. Make sure it has your exact credentials.
What I did was hardcoding my username and password (it is not recommended to do it for security purposes) :
class Config:
SECRET_KEY=os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI')
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 465
MAIL_USE_SSL= True
MAIL_USERNAME='youremailhere'
MAIL_PASSWORD='yourpasswordemailhere'
... and then make sure you have the Less Secure App Access turned on in your google account, you'll find it here -> https://myaccount.google.com/lesssecureapps
I've been trying for some time to be able to receive emails with Django from a website I'm developing. Now, I haven't deployed it yet, and I am using the Django Development Server, and I don't know if this affects it.
Here is my settings.py configuration:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'my_email#gmail.com'
EMAIL_HOST_PASSWROD = 'my_password'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
DEFAULT_TO_EMAIL = EMAIL_HOST_USER
Then, through the root folder of the project I run python manage.py shell, and type the following:
>>> import django
>>> from django.conf import settings
>>> from django.core.mail import send_mail
>>> send_mail('test', 'test', settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], fail_silently=False)
And what I receive back is the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages
sent = self._send(message)
File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send
self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n'))
File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/smtplib.py", line 866, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthErrorv11sm8729581qkl.88 - gsmtp', 'my_email#gmail.com')
I have enabled the option to allow less secure applications.
I tried, when using 2-step verification, to input, instead of EMAIL_HOST_PASSWORD = "my_password", to input EMAIL_HOST_PASSWORD = 'myapplicationpassword' provided by google. It didn't work.
Then I have disabled the 2-step verification and changed from the application password back to my actual password, and the error remains.
Am I doing something wrong? Has Google somehow blocked these types of application? Would I do better if I ran my own mail server?
Make sure that you do the following two things:
Go to App passwords for 2-factor authentication, or look into "Less secure app access" if you're not using MFA. The password google provides when setting up as is a 16 digit code that includes spaces, they count.
Make sure the settings imported or password set and/or retrieved is in the same terminal shell:
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
export EMAIL_PASSWORD="xxxx xxxx xxxx xxxx"
If you are using Google SMTP, Google has introducted a new security feature which blocks use of SMTP directly. In order to use Google SMTP, you need to sign into your Google account and enable access to less secure app. This option os present under Security Checkup under My Account. See the screenshot below.
I tried to edit bash_profile, bashrc, zshrc, profile etc. and nothing worked. If the variables are returning "None" try this :
As mentioned in this link python-dotenv create an .env file (preferably in the root directory of your project) and put your credentials into it. Then in settings.py (if you are using django), use the following code:
from pathlib import Path
from dotenv import load_dotenv
env_path = Path('Path to the .env file')
load_dotenv(dotenv_path=env_path)
Then access the variable using the following code and you should be fine:
os.environ.get('var_name')
this is my settings.py :
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
EMAIL_PORT = '465'
EMAIL_HOST_USER = config_data['EMAIL_HOST_USER']
EMAIL_HOST_PASSWORD = config_data['EMAIL_HOST_PASSWORD']
EMAIL_USE_SSL = True
I have verified the email addresses and have also generated SMTP credentials which I downloaded the credentials containing the IAM username, Smtp username, Smtp password. I used the smtp username for EMAIL_HOST_USER and smtp password for EMAIL_HOST_PASSWORD.
In django, I sent an email with this line (admin#admin.com is replaced with a gmail account that is in the verified email list) :
send_mail("Subject", "content", "admin#admin.com", [email], fail_silently=False)
That did not work. Sending a test email from the SES console (select one of the email in verified emails and click send a test email button) works though.
This document says that I can send email via command line with openssl command. So, i did ssh to the EC2 machine, and use :
openssl s_client -crlf -quiet -starttls smtp -connect email-smtp.us-east-1.amazonaws.com:25
Notice that i used 25 here, when i used port 465, it outputed :
didn't found starttls in server response, try anyway...
write:errno=32
So instead I tried port 25, It connected (250 OK) and then I typed :
AUTH LOGIN
334 VXNlcm5hbWU6
SMTP_USER
334 UGFzc3dvcmQ6
SMTP_PASSWORD
but it outputted : 535 Authentication Credentials Invalid. Could it be I used a wrong credentials? but I copy the username and password straight from the smtp user and password generation page.
I also tried to attach AmazonSESFullAccess policy to all of the IAM users but nothing happened.
I use the Django 1.8.2. Tried Django-ses but it did not work too (syntax error when running the tests, it does not support python 3?)
UPDATE
I changed the port to 587 and use USE_TLS True and now I can send_mail from django shell. I put the function in my app views.py :
def test_email(request):
send_mail("title", "content", "abc#gmail.com", ["def#gmail.com"], fail_silently=False)
return get_return_object(request, status_code=1)
and in urls.py I put this inside the urlpatterns :
url(r'^test_email/$', views.test_email, name="test_email"),
and when I visited the URL, nothing happens. I call the same function test_email from the shell and it works.
UPDATE
It turns out that I can also use port 465 and USE_SSL True and be able to send_mail from django shell. but still it does not work in views.py
2020 update
As the documentation says here: Django Email Documentation and Email_use_ssl
I am using Django 3.0 at this moment, and the documentation says that you can use
EMAIL_USE_SSL = True
... It is generally used on port 465
I make my think works and send emails using AWS SES and port 465 service using that line instead EMAIL_USE_TLS = True :)
If you use port 465:
Install django-smtp-ssl using pip
pip install django-smtp-ssl
then change EMAIL_BACKEND in settings.py as follows:
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
If you use port 587:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
I am attempting to send an email in Python, through Gmail. Here is my code:
import smtplib
fromaddr = '......................'
toaddrs = '......................'
msg = 'Spam email Test'
username = '.......'
password = '.......'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
I get the error:
Traceback (most recent call last):
File "email_send.py", line 18, in <module>
server.login(username, password)
File "C:\.....\Python\lib\smtplib.py", line 633
, in login
raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepte
d. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=1425
7\n5.7.8 {BADCREDENTIALS} s10sm9426107qam.7 - gsmtp')
This seems to be a problem with the login. I am certain that my login details are correct, except for one thing. Should username be "blah#gmail.com", or simply "blah"? I tried both, same error.
Any idea whats wrong?
NOTE: all the periods are instead of password/email/file paths/etc.
UPDATE:
This feature is no longer supported as of May 30th, 2022. See https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637896899107643254-869975220&p=less-secure-apps&rd=1#zippy=%2Cuse-an-app-password
ORIGINAL ANSWER (No longer working):
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:
https://support.google.com/accounts/answer/6010255
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:
https://www.google.com/settings/security/lesssecureapps
Once that is set (see my screenshot below), it should work.
Login now works:
smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('me#gmail.com', 'me_pass')
Response after change:
(235, '2.7.0 Accepted')
Response prior:
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:
https://accounts.google.com/DisplayUnlockCaptcha
Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.
This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:
235 == 'Authentication successful'
503 == 'Error: already authenticated'
The message says to use the browser to sign in:
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.
UPDATE:: See my answer here:
How to send an email with Gmail as provider using Python?
I had the same issue. The Authentication Error can be because of your security settings, the 2-step verification for instance. It wont allow third party apps to override the authentication.
Log in to your Google account, and use these links:
Step 1 [Link of Disabling 2-step verification]:
https://myaccount.google.com/security?utm_source=OGB&utm_medium=act#signin
Step 2: [Link for Allowing less secure apps]
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none
It should be all good now.
I am also faced with the same error message when I try to use smtplib. The error message was like this;
error (535, b'5.7.8 username and password not accepted.
Google has changed access to less secure apps. Before that, there was a field to give access to. Now you can follow these steps;
Go to Google Account Page>Security>Signing in to Google section
turn on 2-Step Verification. You need this feature on.
When 2SV is on, go to App Password and generate new-app-password for mail access. It will generate it for you, then use this password in gmail_password function in Python.
gmail_password='google_generate_it_for_you'
If you're using smtp.gmail.com, then you have to do the following:
Turn on the less secure apps
You'll get the security mail in your gmail inbox, Click 'Yes,it's me' in that.
Now run your code again.
Denied
The solution of using "Access for the less secure app" in Gmail has been denied (find more here).
Update
By the way, you can get access to the gmail account by the solution proposed by Google, called "App password". The solution is simple:
1. Active two-step verification of the corresponding account.
2. Create an app password.
3. Exactly do the same implementation that you have for sending an email (explained in your question).
Except, replace the password with the generated app password (a sixteen digit password).
For more details you can also follow this post (it's working well for me).
I had same issue. And I fix it with creating an app-password for Email application on Mac.
You can find it at my account -> Security -> Signing in to Google -> App passwords.
below is the link for it.
https://myaccount.google.com/apppasswords?utm_source=google-account&utm_medium=web
If you turn-on 2-Step Verification, you need generate a special app password instead of using your common password.
https://myaccount.google.com/security#signin
if you are getting error this(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o60sm2132303pje.21 - gsmtp')
then simply go in you google accountsettings of security section and make a less secure account and turn on the less secure button
I had the same issue , i solved this by allowing "less secure app access" . This can be found in Security tab on Google Account:
Dec, 2022 Update:
You need to use an app password to allow your app to access your google account.
So, you need to:
generate an app password following my answer explaining how to generate an app password.
assign the generated app password to password in your code as shown below:
import smtplib
fromaddr = '......................'
toaddrs = '......................'
msg = 'Spam email Test'
username = '.......'
password = 'xylnudjdiwpojwzm' # Here
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
Enable 2FA for your Google account
Then set an app password for your app
Use that new password
For email created by G-Suite or Google Workspace, you have to ask your admin to activate the Gmail app and assigned it to your email account. Without this step, trying either above methods still does not work.
Oct 3 2022
As per all the answers mentioned above.
Enabling 2Factor Authentication and creating an App Pasword does the trick with SMTP.
NOTE: Less secure apps toggle doesn't work anymore tbh?(Others confirm?)
Update after May 30th, 2022 :
To solve this problem it is necessary to activate two-step
verification on your Gmail account :
https://myaccount.google.com/u/1/security
Then you will have access to a new page to create an App Password :
https://myaccount.google.com/u/1/apppasswords
Finally, using this password on your django application should solve the problem.
Tutorial for more information: https://www.youtube.com/watch?v=sCsMfLf1MTg
less secure apps can now only be used in gmail if you turn on 2 factor auth and then generate an app password for a custom app
these steps worked for me :)
follow these steps https://myaccount.google.com/security
It is no longer possible as google has removed support for Less secure apps.
However you can still use App Passwords
Documentation from google -https://support.google.com/accounts/answer/185833?hl=en
Create & use App Passwords
If you use 2-Step-Verification and get a "password incorrect" error when you sign in, you can try to use an App Password.
Go to your Google Account.
Select Security.
Under "Signing in to Google," select App Passwords. You may need to sign in. If you don’t have this option, it might be because:
2-Step Verification is not set up for your account.
2-Step Verification is only set up for security keys.
Your account is through work, school, or other organization.
You turned on Advanced Protection.
At the bottom, choose Select app and choose the app you using and then Select device and choose the device you’re using and then Generate.
Follow the instructions to enter the App Password. The App Password is the 16-character code in the yellow bar on your device.
Tap Done.
Tip: Most of the time, you’ll only have to enter an App Password once per app or device, so don’t worry about memorizing it.
In my case, I allowed the access, but the problem was that I was using server.login('Name <email>', password). Please, make sure to use only your email here: server.login('youremail#gmail.com', password).
Response after change:
(235, '2.7.0 Accepted')
Response prior:
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials 130sm13119106qkh.99 - gsmtp')
Try turning on less secure apps and make sure that you have smtp.gmail.com or for different search up