Django Email Management Command

14 October 2020

Email Here we share a small django management command that sends an email. This command is useful because it will use the same email credentials the rest of your django api is using to send emails. So you can use this as a sanity check to see if your settings are correct.

# <your app>/management/commands/

from django.conf import settings
from django.core.mail import send_mail
from import BaseCommand

class Command(BaseCommand):
    Sends an email to the provided addresses.

    help = "Sends an email to the provided addresses."

    def add_arguments(self, parser):
        parser.add_argument("emails", nargs="+")

    def handle(self, *args, **options):
        self.stdout.write(f"send_email from: {settings.EMAIL_FROM_FIELD}")
        for email in options["emails"]:
                    "Django test email",
                    "a simple email body",
            except BaseException as e:
                self.stdout.write(f"Problem sending email: {e}")

To use this ssh into your api and run:

$ python send_email

If your django api has working email smtp settings you should see a test email at the receiving addresses.

In local development you can use something like mailhog to preview the emails locally. It would look like this

test email in mailhog

If you need help solving your business problems with software read how to hire me.

comments powered by Disqus