Hi everyone! I am working on setting up a web application using Flask. I want to be able to send users emails, like when they sign up for example. I followed a tutorial (Sending Emails with Flask - Step-by-Step Flask-Mail Guide | Mailtrap Blog - Sending emails in Flask) and it was working until I reorganized the code to be more than one file, which I need to do to make it work with the rest of my project. Since then, I am getting an error
File “C:\Flask Mail\service\routes.py”, line 6, in index
mail.send(msg)
NameError: name ‘mail’ is not defined
I am clearly doing something wrong, but I don’t know what. My file structure is like this:
Flask Mail
env
service
| pycache
| init.py
| extensions.py
| routes.py
run.py
My code looks like this:
#__init__.py
from flask import Flask
from service import routes
from .extensions import mail
def create_app(config_file=None):
# create and configure the app
app = Flask(__name__)
app.add_url_rule("/", view_func=routes.index)
app.config['MAIL_SERVER']='sandbox.smtp.mailtrap.io'
app.config['MAIL_PORT'] = 2525
app.config['MAIL_USERNAME'] = <username from mailtrap>
app.config['MAIL_PASSWORD'] = <password from mailtrap>
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
mail.init_app(app)
return app
#extensions.py
from flask_mail import Mail, Message
mail = Mail()
# routes.py
from flask_mail import Message
def index():
msg = Message('Hello from the other side!', sender = 'peter@mailtrap.io', recipients = ['paul@mailtrap.io'])
msg.body = "Hey Paul, sending you this email from my Flask app, lmk if it works"
mail.send(msg)
return "Message sent!"
# run.py
from service import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug = True)
What am I missing here?
Top comments (0)