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.
I need to check whether a username and password of a gmail account are valid. How can I do that using python?
Google doesn't allow access to Gmail accounts from third-party apps without the consent of the account owner.
This is of course a good idea to keep Google accounts more secure and protect sensitive information.
See: Google Third-party sites & apps with access to your account
Now, there are a couple of options I can think of:
1. If you are trying to access accounts that you own or that have approved access to your app you could use smptlib to start a SMTP(Simple Mail Transfer Protocol) client session.
After you established a connection you can attempt to login to your account and print messages appropriately.
For Example:
import smtplib
username = "gmailaddress"
password = "yourpassword"
server = smtplib.SMTP('smtp.gmail.com', 587) #smtp settings, change accordingly.
server.ehlo()
server.starttls() # secure connection
try:
server.login(username, password)
print("valid account")
except:
print("invalid account")
2. Google's API - this option, while it may be more suitable will probably also require authorization and further research. Google has an API for many of it's services and even provides examples. See: Google API Python Quickstart
An API provides a way for you to interact with with a companies online services securely and the way they were intended.
The limited access to Google accounts may seem exaggerated but that's how your account stays secure :) Good luck!
I'm trying to get Flask-Mail setup on in Flexible ENV on Google App Engine. Flask-Mail works on my localhost using the credentials for a domain I am trying to use to send the mail. However, when using it on GAE through my API it returns a 502 error, however it shows no error messages in the logs or console. Going through the documentation for GAE Flexible it doesn't mention anything about NOT being able to use it, however it doesn't show how one would setup Flask-Mail either.
I have this..
mail = Mail()
print('1') // We Get here
msg = Message("Hello",
sender="me#mydomain.com",
recipients=["me#mydomain.com"])
print('2') // We get here
msg.body = 'Testing'
print('3') // We get here
mail.send(msg)
print('4') // This never gets call because I timeout on a 502 before this
I can tell I am not getting any fatal errors because the app stays working. However this fails with the 502. I have tried adding my email to the list of authorized senders but it doesn't seem to have helped.
I would appreciate any feedback. If I forced to use a 3rd party service to send mail it may cause me to move the project off of GAE.
As Ivan posted on his comment, to send email from a GAE app you need to use a mail service. Right now there are 3 options for apps on a flexible environment: Mailgun, MailJet and SendGrid. Choose the one you see better for your app.
After setting up an account on the mail service you have chosen, you have to prepare your code by integrating the parts related to the mail service.
These tutorials should help you establish the mail service for your app:
Mailgun
MailJet
SendGrid
I've had the same error but on a virtual machine on the internet ( linode service ) and it turned out that it has some thing to do with rDNS and some domain name config that you have to set up for your Ip address to get things working correctly , check this
https://www.linode.com/community/questions/19082/i-just-created-my-first-linode-and-i-cant-send-emails-why
def send_one_mail(request):
send_mail('The subject', 'The body to testing', 'userone#example.com',['usertwo#gmail.com'], fail_silently=False)
return HttpResponse("This mail has sent successfull")
And my settings.py is
EMAIL_USE_TLS = True
EMAIL_HOST = 'mail.example.com'
EMAIL_HOST_USER = 'userone#example.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = 'userone#example.com'
SERVER_EMAIL = 'userone#example.com'
I have a view (which works) as shown above, here userone#example.com is sender and usertwo#gmail.com
is the receiver.
How can i check and act according to errors in sending mail?
(I want to show "Some error occured" in such errors)
How can i determine if the usertwo#gmail.com(reciver) exists or not?
(if email can't be reached, i want to show the user that the email doesn't exist)
I am using postfix,dovecot etc. in server.
You can pick up some errors when you use fail_silently = False. Just wrap send_mail in try/except.
When i wanted more control over e-mail sending, then i stopped using django mailing completely and installed lamson instead (lamsonproject.org). You can basically create your own mail server with it, attach your django orm to it and provide detailed feedback about what has happened to your e-mails. If you insert some kind of downloadable content into those e-mails (like images), then you can even give hashes to images and verify this way if e-mail has been opened too. You could do that with django based email sending too. Lamson just gives bit more control over the what and how that goes on after you hit send button.
django-mail-queue
Anyway, i finally ended-up with using the below package.
pip install django-mail-queue
And here is the docs
https://django-mail-queue.readthedocs.org/en/latest/
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