I am working on my website right now and am trying to send a confirmation email when a user creates an account. How can I do this in Python? Can I even do it in Python on my Flask app? I'm really confused right now and could just use some help. Thank you all so much :)
You can use flask_mail for this purpose
To make it work set parameters this way:
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'youremail#gmail.com' # your email
app.config['MAIL_PASSWORD'] = 'your-password' # your password
Also go to your google account security settings and enable 'Less secure app access’, but google doesn’t really like it and still sometimes you can get errors. In this case just try to play with thaws settings, turn things off and on again, at some point it should definitely work (I’m so convinced, cause this totally works for me)
You also can use the app-specific password in google settings.
Here is my properties in settings.py file:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'infobot9#gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
EMAIL_PORT = 587
and here is my send email method:
from django.core.mail import send_mail
def sendConfirmEmail(email, instance, code):
mail_subject = 'Confirmation code {}'.format(code)
message = render_to_string("msg.html", {
'user': instance,
'code': code
})
to_email = email
send_mail(mail_subject, message, 'infobot9#gmail.com', [to_email],
fail_silently=False)
My Django email sending methods work fine in my local host. After deploying it to Heroku I have allowed the login from unknown devices in my Gmail settings. Gmail does not allow the server login to my account and sends me a message:
spicious login attempt blocked
infobot9#gmail.com
Someone tried to log into your account using the password set for them. If it was not you, we recommend that you change your password as soon as possible.
Unknown Device
April 4, 11:39
Near this place: Dublin, Ireland
176.34.163.6 (IP address)
Should I set extra parameters in my settings.py file or I need change my Gmail account settings?
I urge you not to use Gmail for sending email in production. It's not designed for that, and as you've discovered there are measures in place to prevent it from being used as a spam relay. Even if you're sending legitimate email, Gmail is going to make things difficult for you.
Instead, use a service that's designed to send mail from hosted applications like SendGrid or Mailgun. These are both listed among Heroku's addons and both have free starter plans. Pick one and go through its getting sarted guide. Not only will this work better with small volumes of mail, it sets you up nicely for growth.
Allow less secure apps
Display Unlock Captcha
If you still want to use Gmail, #Pierre Monico's answer will work. I just wanted to make an edit. After allowing less secure apps to sign in to your account and Display Unlock Capatcha you should still keep two things in mind. First be sure to be logged into your browser through the account which you are using in your app to send email so that Capatch should be unlocked for that particular account and the second thing is that Google only allows Display Unlock Capatcha for Only 10 minutes . Thus if you want to use it again and again just keep Display Unlock Capatcha page open in your browser and keep it refreshing after sometime.
Also if you have 2 factor authentication enabled then these steps won't work. Those accounts have different procedure.
Above mentioned answers didn't work for me. So here's how I did it. Basically, you need to configure an app password.
Go to your Gmail account
Security > in 'Signing in to Google' section
Turn on 2-Step Verification
Set app password
and finally, need to configure settings.py or .env file(follow's the env),
EMAIL_HOST_USER=your_email#gmail.com
EMAIL_HOST_PASSWORD=generated_app_password
Tip
Using python-decouple makes it much easier to handle .env data
Recently I started to get
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.soundcloud.com/oauth2/token
using soundcloud (0.5.0) Python library.
It happens in
client = soundcloud.Client(client_id='id',
client_secret='secret',
username='user#mail.com',
password='passwd')
I double checked my credentials to make sure they are not the cause. I tried to get a Client instance from different IPs and different machines. At some random times during a day I can get a Client instance, but 99.99% of the day I get the error.
Does the error mean I was banned for some reason?
It may be helpful, I solved a similar problem by reading the username and password from the configuration file.
Try:
# config.ini
[my_app]
CLIENT_ID = enter_your_id
CLIENT_SECRET = enter_your_secret
USERNAME = enter_username
PASSWORD = enter_password
Install configparser from Python 3.8 for Python 2.6+: pip install configparser.
See the great documentation for more details.
import configparser
config = configparser.RawConfigParser()
config.read('config.ini')
my_id = config.get('my_app', 'CLIENT_ID')
my_secret = config.get('my_app', 'CLIENT_SECRET')
my_user = config.get('my_app', 'USERNAME')
my_pass = config.get('my_app', 'PASSWORD')
client = soundcloud.Client(client_id=my_id,
client_secret=my_secret,
username=my_user,
password=my_pass)
Probably you are using a third-party app to access your account,
in case you are using Gmail service for your purpose, consider allowing third-party apps to have access to your Gmail account, how are you going to do that:
Go to https://myaccount.google.com/security
Use Two-Step-Authentication and enable it.
Create an App Password, Select App > Mail | Select Device > Windows Computer.
And use the password given
And that should solve your issue.
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