How to automatic email in Django

You can send emails automatically by doing the following.

Automatic email step

1. Prepare a mail server
2. Add information of mail server
3. Add function of automatic mail

1. Prepare a mail server

First of all, You need to prepare a mail server.

In this article, I introduce how to use Gmail.

If you use Gmail, you can send 500 mails per day automatically.

Maybe you have Google account, but you need to get app password when you use Gmail server.

So get Google app password for reference the following link.

Sign in with app passwords

2. Add information of mail server

Next, You need to set information of mail server in settings.py of Django.

In “EMAIL_HOST”, “EMAIL_PORT” and “EMAIL_USE_TLS”, just copy and paste it.

But in “EMAIL_HOST_USER” and “EMAIL_HOST_PASSWORD”, You need to rewrite to your account.

By the way, “EMAIL_HOST_PASSWORD” is App Password that introduce in 1.

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'Google account name'
EMAIL_HOST_PASSWORD = 'Google app password'
EMAIL_USE_TLS = True

3. Add function of automatic mail

At the end, You need to add function of automatic mail.

You can send emails automatically by using the following code.

from django.core.mail import send_mail

send_mail(
    subject = "text_subject",
    message = "text_message",
    from_email = "xxx@gmail.com", # sender address
    recipient_list = ["yyy@gmail.com", "zzz@gmail.com"], # delivery address
    fail_silently = False,
)