Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.
- Model -> models.py
- View -> views.py
- Controller -> __init__.py
Let's say your Flask app has the following structure.
├── main.py
├── database (directory)
│ ├── example.db
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── models.py
│ ├── templates (directory)
│ │ ├── base.html
│ │ ├── home.html
│ │ ├── results.html
│ └── static (directory)
│ └── custom.css
First, use the pip install command to install the Flask-Mail package.
pip install aws-secretsmanager-caching
Or, you can specify the version to install
pip install Flask-Mail==0.9.1
Or, better yet, use a requirements.txt file.
Flask-Mail==0.9.1
And then install the packages using the requirements.txt file.
pip install --requirement requirements.txt
Your controller (__init__.py) could have something like this.
from flask import Flask
from flask_mail import Mail
mail = Mail()
def app():
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'mail.example.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USERNAME'] = 'john.doe'
app.config['MAIL_PASSWORD'] = 'itsasecret'
app.config['MAIL_USE_TLS'] = False
mail = Mail(app)
return app
Your view (views.py in this example) could have something like this.
from . import mail
from flask_mail import Message, Mail
@views.route('/sendEmail')
def email():
msg = Message('Subject Line', sender = 'no-reply@example.com', reply_to = 'john.doe@example.com', recipients = ['jane.doe@example.com'])
msg.body = "Hello World"
mail.send(msg)
try:
mail.send(msg)
except Exception as exception:
return exception
else:
return "successfully sent email"
Here is how you could attach a file to the email.
IMPORTANT
The magic module is used to determine the MIME type (e.g. text/plain or application/pdf) and encoding (e.g. us-assii or utf-8) and then uses a try except block to NOT attach the file if doing so would raise an exception. The magic module can be installed using "pip install python-magic"
from . import mail, magic
from flask_mail import Message, Mail
@views.route('/sendEmail')
def email():
msg = Message('Subject Line', sender = 'no-reply@example.com', reply_to = 'john.doe@example.com', recipients = ['jane.doe@example.com'])
msg.body = "Hello World"
mimetype = mime.from_file("C:\\Users\\john.doe\\helloworld.txt")
blob = open("C:\\Users\\john.doe\\helloworld.txt", 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob)
file = open("C:\\Users\\john.doe\\helloworld.txt")
try:
msg.attach("helloworld.txt", "application/txt", file.read())
except Exception as exception:
print(exception)
file.close()
try:
mail.send(msg)
except Exception as exception:
return exception
else:
return "successfully sent email"
Did you find this article helpful?
If so, consider buying me a coffee over at