Anymail 1-2-3

Here’s how to send a message. This example uses Mailgun, but you can substitute Mailjet or Postmark or SendGrid or SparkPost or any other supported ESP where you see “mailgun”:

  1. Install Anymail from PyPI:

    $ pip install django-anymail[mailgun]
    

    (The [mailgun] part installs any additional packages needed for that ESP. Mailgun doesn’t have any, but some other ESPs do.)

  2. Edit your project’s settings.py:

    INSTALLED_APPS = [
        # ...
        "anymail",
        # ...
    ]
    
    ANYMAIL = {
        # (exact settings here depend on your ESP...)
        "MAILGUN_API_KEY": "<your Mailgun key>",
        "MAILGUN_SENDER_DOMAIN": 'mg.example.com',  # your Mailgun domain, if needed
    }
    EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"  # or sendgrid.EmailBackend, or...
    DEFAULT_FROM_EMAIL = "[email protected]"  # if you don't already have this in settings
    
  3. Now the regular Django email functions will send through your chosen ESP:

    from django.core.mail import send_mail
    
    send_mail("It works!", "This will get sent through Mailgun",
              "Anymail Sender <[email protected]>", ["[email protected]"])
    

    You could send an HTML message, complete with an inline image, custom tags and metadata:

    from django.core.mail import EmailMultiAlternatives
    from anymail.message import attach_inline_image_file
    
    msg = EmailMultiAlternatives(
        subject="Please activate your account",
        body="Click to activate your account: http://example.com/activate",
        from_email="Example <[email protected]>",
        to=["New User <[email protected]>", "[email protected]"],
        reply_to=["Helpdesk <[email protected]>"])
    
    # Include an inline image in the html:
    logo_cid = attach_inline_image_file(msg, "/path/to/logo.jpg")
    html = """<img alt="Logo" src="cid:{logo_cid}">
              <p>Please <a href="http://example.com/activate">activate</a>
              your account</p>""".format(logo_cid=logo_cid)
    msg.attach_alternative(html, "text/html")
    
    # Optional Anymail extensions:
    msg.metadata = {"user_id": "8675309", "experiment_variation": 1}
    msg.tags = ["activation", "onboarding"]
    msg.track_clicks = True
    
    # Send it:
    msg.send()
    

Problems? We have some Troubleshooting info that may help.

Now what?

Now that you’ve got Anymail working, you might be interested in: