sslgmailsmtplibflask-mail

Flask Mail & GMail Settings - Very Confused


I have been learning Flask (with the help of many very generous YouTuber's)
I thought adding a 'Subscribe' function that sends an email notification via GMail would be fairly straightforward.
After a few days of Googling around I am getting the following results from each combination of port 465 or 587, SSL and/or TLS enabled/disabled. Less secure apps option in Gmail is permitted.

from flask import Flask  
from flask_mail import Mail, Message

app = Flask(__name__)

app.config['MAIL_DEBUG'] = True  
app.config['TESTING'] = False  
app.config['MAIL_SERVER'] = 'smtp.gmail.com'  
app.config['MAIL_PORT'] = see results below  
app.config['MAIL_USE_TLS'] = see results below  
app.config['MAIL_USE_SSL'] = see results below  
app.config['MAIL_USERNAME'] = None  
app.config['MAIL_PASSWORD'] = 'secret_password'  
app.config['MAIL_DEFAULT_SENDER'] = 'me@gmail.com'  
app.config['MAIL_MAX_EMAILS'] = None  
app.config['MAIL_SUPPRESS_SEND'] = False  
app.config['MAIL_ASCII_ATTACHMENTS'] = False  

mail = Mail(app)

@app.route('/')  
def home():  
    msg = Message('Test Message from Flask Mail', recipients=['you@gmail.com'])  
    mail.send(msg)  
    return 'OK'

if __name__ == '__main__':  
    app.run(debug=True)

Results in -

Port    SSL TLS Result  
465 On  On  smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server  
465 Off On  smtplib.SMTPServerDisconnected: Connection unexpectedly closed  
465 On  Off smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required  
465 Off Off smtplib.SMTPServerDisconnected: Connection unexpectedly closed  
            
587 On  On  ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number  
587 Off On  smtplib.SMTPSenderRefused: (530, b'5.7.0 Authentication Required  
587 On  Off ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number  
587 Off Off smtplib.SMTPSenderRefused: (530, b'5.7.0 Must issue a STARTTLS command first  

SSL version is -

import ssl
ssl.OPENSSL_VERSION
'OpenSSL 1.1.1f 31 Mar 2020'

This SMTPLIB works just fine -

import smtplib

smtp_server = 'smtp.gmail.com'  
port = 587  
sender = 'me@gmail.com'  
password = 'secret'  
receiver = 'you@gmail.com'  
msg = "Test Message from SMTPLIB"  

server = smtplib.SMTP(smtp_server, port)  
server.starttls()  
server.login(sender,password)  
server.sendmail(sender, receiver, msg)  

Solution

  • It's been a few years now but worked for me (looking at an old code) was

    app.config['MAIL_PORT'] = 587
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USE_SSL'] = False
    app.config['MAIL_USERNAME'] = <your email address> # should not be None as you currently have in your code
    

    Note: I only used this code for testing on my local machine. I switched to Google App Engine mail and later SendGrid