2

I have a simple CRUD webapp set up in Python/Flask, when one particular function is activated (approving a request) I'd like to send an email notification to the user, but for all I've tried I can't get the email to send through my code.

Here is my config file with all the relevant environment variables set (inside of a Config object):

MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT=465
MAIL_USE_SSL=True
MAIL_USERNAME = '**@gmail.com'
MAIL_PASSWORD = '**'

I have also tried calling app.config.update(those values) in my app/init.py file. Here is the current code to do so

mail = Mail()

def create_app(config_name):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('./config.py')
    app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=465,
    MAIL_USE_SSL=True,
    MAIL_USE_TLS=False,
    MAIL_USERNAME = '**@gmail.com',
    MAIL_PASSWORD = '**')

    mail.init_app(app)

And finally here is the code where I actually attempt to send the email:

msg = Message(html=html, sender='**@gmail.com', subject='Your Reservation for %s' % reservation.item.name, recipients=['**'])
mail.send(msg)

Additionally, it currently fails silently and I don't know how to even view what error is happening. Any help is much appreciated!

Wasdo
  • 71
  • 3
  • 9

3 Answers3

2

My suggestion in the comments was indeed the answer to the question.

Enabling "Less Secure Apps" in the Google Account settings was the necessary step to fix the hangup the OP was experiencing. This link from Google's support page walks you through how to enable this option.

BrettJ
  • 1,176
  • 2
  • 17
  • 33
1

I think, you should switch your sending protocol to TLS

this is sample from my project

MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=587,
MAIL_USE_TLS=True,
MAIL_USERNAME = '**@gmail.com',
MAIL_PASSWORD = '**'

for me this works very well.

Roman Kazakov
  • 697
  • 7
  • 12
0

Now that Google is removing the less-secure app access feature due to security reasons, the best way to get around this is to use Sendgrid. They provide 100 free emails per day forever. You can register your same Gmail address as a single sender in SendGrid. Generate an API key and use it in your flask app to send emails.

For reference: Sending Emails from Python Flask Applications With Twilio SendGrid