Question

I'm having issues with my email getting to where it needs to be. I've set up the config file of my Flask app on Heroku like so:

class ProductionConfig(Config):
    DATABASE_URL = 'postgres://stuff'
    MAIL_SERVER = os.environ.get('MAILGUN_SMTP_SERVER', 'localhost')
    MAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT', 25)
    MAIL_USERNAME = os.environ.get('MAILGUN_SMTP_LOGIN', None)
    MAIL_PASSWORD = os.environ.get('MAILGUN_SMTP_PASSWORD', None)
    DEFAULT_MAIL_SENDER = 'myemail@myemail.com'
    MAIL_USE_SSL = True

with the Flask-Mail library:

    from flask.ext.mail import Mail, Message

    mail = Mail(app)

    def send_mail(to, title, msg):
      email = Message(title, recipients = [to], body = msg)

      return mail.send(email)

But sure enough, I try to send an email and it never gets there. Did I do something incorrectly? Am I missing something? (I've removed the real DB URL and email address in case you're wondering.)

Much thanks in advance.

Was it helpful?

Solution

According to the documentation, the correct SMTP server for Mailgun is smtp.mailgun.org not localhost and the port is 587 not 25. Maybe changing those would fix it up. Looks like the login and password are required as well.

You might have more success using the Mailgun API instead of Flask-Mail. I found it to be easier to use in my own applications.

This is the config and a little utility function I wrote to send mail via Mailgun on Heroku using the requests library:

import requests    

app = Flask(__name__)
app.config['MAILGUN_KEY'] = 'YOUR-KEY-HERE'
app.config['MAILGUN_DOMAIN'] = 'YOUR-MAILGUN-DOMAIN'

@app.route('/', methods=['GET', 'POST'])
def home():
    ...
    send_mail(...)

def send_mail(to_address, from_address, subject, plaintext, html):
    r = requests.\
        post("https://api.mailgun.net/v2/%s/messages" % app.config['MAILGUN_DOMAIN'],
            auth=("api", app.config['MAILGUN_KEY']),
             data={
                 "from": from_address,
                 "to": to_address,
                 "subject": subject,
                 "text": plaintext,
                 "html": html
             }
         )
    return r

If you login to Heroku and click on the Mailgun Add-on, it will take you to the Mailgun control panel where you can get the key and domain needed in the code above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top