I can't send emails using Flask-Mail when I initialize the app from another file

174 Views Asked by At

Im trying to send an email when certain button is pressed. It works when I change app = Flask(name) directly instead of app = create_app() in the app.py

app.py

from website import create_app
from flask import Flask, request, render_template
from flask_mail import Mail, Message
# import schedule
# import time 

app = create_app()

mail = Mail(app)

def send_email_notification(email, body):
    msg = Message('Scheduled Notification', sender='[email protected]', recipients=['myemail']) #I use my real email btw, I just remove it for privacy
    msg.body = body
    mail.send(msg)

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        email = request.form.get('email')
        body = request.form.get('note')
        send_email_notification(email=email, body=body)
        return "Email sent successfully"
    return render_template('home.html')  

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

init.py

from flask import Flask
from flask import request 
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
from flask_mail import Mail, Message

mail = Mail()


db = SQLAlchemy()
DB_NAME = "database.db"


def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'hjshjhdjah kjshkjdhjs'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 587
    app.config['MAIL_USERNAME'] = ''  # Replace with your Gmail email
    app.config['MAIL_PASSWORD'] = ''  # Replace with your Gmail password
    app.config['MAIL_USE_TLS'] = True
    app.config['MAIL_USE_SSL'] = False
    db.init_app(app)

    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')

    from .models import User, Note
    
    with app.app_context():
        db.create_all()

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app


def create_database(app):
    if not path.exists('website/' + DB_NAME):
        db.create_all(app=app)
        print('Created Database!')

So I want to know how to send the email with create_app()

I have tried a lot of things. Like doing it directly on app.py, but it's a mess. Im beginner, so please a beginner-friendly explanation please

0

There are 0 best solutions below