flask mail works perfectly on my local host but it is failing to work on heroku. Below is my setup code
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = '@gmail.com'
app.config['MAIL_PASSWORD'] = '*****'
mail = Mail(app)
@app.route("/mymessage" ,methods= ['POST','GET'])
def mymessage():
em = request.form['email']
mm = request.form['message']
msg = Message('Hello', sender = '@gmail.com', recipients =
['@gmail.com'])
msg.body = mm + " " + 'email address of client :' + em
mail.send(msg)
flash("Message sent successful")
return redirect(url_for('home'))
I get this error "2021-07-10T16:36:34.785576+00:00 app[web.1]: smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 YJZzLi6GK2jMF6AunHXhEoSyz2r6fSOYLB4ABgjP0jNdTWHh3ig-fhlvwc7oxm-quoLVa\n5.7.14 Z7CHpvU2lMufxnPm_0Dsc3p1uWgZhenvZQpb2TdWaZTZ-Sg_wojgwf4zlOlBe44O>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 m6sm3480925qtx.9 - gsmtp')
2021-07-10T16:36:34.787223+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/mymessage" host=buykev.herokuapp.com request_id=fe5ec81e-6d2f-4f8a-b148-a37a15c0bc28 fwd="102.176.94.10" dyno=web.1 connect=4ms service=871ms status=503 bytes=0 protocol=https"
Google blocks your signin attempt from heroku. You need to enable less secure apps and use an app password for your mail account to solve this.
First we have to enable two step verification then only we can use the app password. After enabling the 2-step verification, go to app password and select app as mail and device (I selected windows computer) after you get the app password replace your current password with it. and try sending the mail again. It will work.
app.config['MAIL_PASSWORD'] = 'your_app_password_here'