pythondjangoemailheroku

Django email sending on Heroku


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?


Solution

  • 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.