pythonemailflaskautomationmail-sender

Python Flask - Email Sender Does not Work


I am trying to sending auto mail from my real mail adres to other mail adres. I use my real password for MAIL_PASSWORD value. What am I doing wrong with coding. I dont get any errors but I dont get any mails neihter... I need help to figure it out.

from flask import Flask
from flask_mail import Mail, Message

app = Flask(__name__)
mail= Mail(app)

app.config['MAIL_SERVER']='smtp.gmail.com' #or localhost what is the difference between localhost and smtp I dont know yet
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'mymail@gmail.com'
app.config['MAIL_PASSWORD'] = 'realmailpassword'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

@app.route("/")
def index():

    try:
        msg = Message('Hello', 
                    sender='mymail@gmail.com',
                    recipients='receiver@gmail.com')
        msg.body = 'my first auto mail'
        mail.send(msg)
        print('mail has been sent')
    except Exception:
        print('mail could not be send')

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

Solution

  • the mail= Mail(app) should be moved after setting all the mail related variables.

    Also as other posts suggest, you should use different gmail port, switch SSL to TLS. here is your script modified:

    import traceback
    from flask import Flask
    from flask_mail import Mail, Message
    
    app = Flask(__name__)
    
    app.config['MAIL_SERVER']='smtp.gmail.com' #or localhost what is the difference between localhost and smtp I dont know yet
    app.config['MAIL_PORT'] = 587
    app.config['MAIL_USERNAME'] = 'mymail@gmail.com'
    app.config['MAIL_PASSWORD'] = 'realmailpassword'
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USE_SSL'] = False
    
    mail= Mail(app)
    
    @app.route("/")
    def index():
    
        try:
            msg = Message('Hello', 
                        sender='mymail@gmail.com',
                        recipients='receiver@gmail.com')
            msg.body = 'my first auto mail'
            mail.send(msg)
            print('mail has been sent')
        except Exception:
            print('mail could not be send, details: ' + traceback.format_exc())
    
        return "Done"
    
    if __name__ == '__main__':
       app.run(debug = True)
    

    but you will end up getting a Gmail error:

    smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8  https://support.google.com/mail/?p=BadCredentials a10-20020a170414149065f8a00b414100921414595899cfcsm11531412673eju.53 - gsmtp')
    

    because Gmail stopped accepting user/password authentications.