Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send emails with Django to my gmail account

Tags:

django

gmail

I've tried sending emails with my Gmail account in Django, but I always get errors. I tried using a sandbox (Mailtrap) and it worked but using the actual Gmail account doesn't. I've also tried using App Password in my google account but it still doesn't work.

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

EMAIL_HOST = "smtp.gmail.com"

EMAIL_USE_TLS = True

EMAIL_PORT = 587

EMAIL_HOST_USER = "[email protected]"

EMAIL_HOST_PASSWORD = "password"

Error I always get;

SMTPConnectError at /send/
(421, b'Service not available')

This is what shows up

Please how can this be fixed.

like image 776
Chinyere Unamba Avatar asked Oct 19 '25 20:10

Chinyere Unamba


2 Answers

I've done it recently using Google App Password. Follow instructions to get 2-step verification, get the password and then put it in your EMAIL_HOST_PASSWORD enviromental variable with quotes. (EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxxxxx'). The other parameters I've set are as follows:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

Finally I send the emails on my view with send_mail

from django.core.mail import send_mail
like image 155
diml Avatar answered Oct 22 '25 11:10

diml


You have serval options.

Apps password smtp

Does the google account you are using have 2fa enabled, if it does then you can create an apps password. Then take the apps password and use that implace of the password in your code.

XOauth2 smtp

Depending upon the system you are using to send emails it may support Xoauth2 authorization. If it does then you can use that to send emails via the smtp server.

Gmail api. Oauth2 or service accounts

You can switch to using the gmail api, if you have a workspace account then you could use service accounts. If not then you will need to stick with Oauth2 and authorize your appliaton once. This is simarl to using Xoauth2 with the smtp server only you will be going though the gmail api instead.

How to create a Apps Password for connecting to Google's SMTP server.

like image 34
DaImTo Avatar answered Oct 22 '25 10:10

DaImTo