|
| 1 | +""" |
| 2 | +Flask Example - Mail Service implementation in Flask |
| 3 | +Level - Basic |
| 4 | +Author - [Raj Patra](https:github.com/raj-patra) |
| 5 | +""" |
| 6 | + |
| 7 | +# Importing flask module in the project is mandatory |
| 8 | +# An object of Flask class is our WSGI application. |
| 9 | +from flask import Flask, request |
| 10 | + |
| 11 | +from flask_mail import Mail, Message |
| 12 | +from flask_cors import CORS |
| 13 | +from config import Config |
| 14 | + |
| 15 | + |
| 16 | +# Flask constructor takes the name of current module (__name__) as argument. |
| 17 | +app = Flask(__name__) |
| 18 | + |
| 19 | +# Initialize the flask app with the Mail constructor from the flask_mail package. |
| 20 | +mail = Mail(app) |
| 21 | + |
| 22 | +# It is always a good practice to load the app configuration from a different file. |
| 23 | +app.config.from_object(Config()) |
| 24 | + |
| 25 | +# Enabling CORS allows our API to be used from all hosts. |
| 26 | +cors = CORS(app, resources={r"/*": {"origins": "*"}}) |
| 27 | + |
| 28 | +# Index route for the welcome message |
| 29 | +@app.route('/', methods=["GET", "POST"]) |
| 30 | +def index(): |
| 31 | + if request.method == 'GET': |
| 32 | + return {"message": "Welcome to Demo-Flask-App"}, 200 |
| 33 | + |
| 34 | + |
| 35 | +@app.route('/sendMail', methods=["POST"]) |
| 36 | +def mail(): |
| 37 | + # Self-explanatory |
| 38 | + sender = Config.MAIL_SENDER |
| 39 | + recipients = ["john.doe@test.com", "jane.doe@test.com"] |
| 40 | + |
| 41 | + title = Config.MAIL_TITLE |
| 42 | + body = Config.MAIL_BODY |
| 43 | + |
| 44 | + # Sending the mail using the current app context |
| 45 | + with app.app_context(): |
| 46 | + # Starting the mail service. |
| 47 | + # The credentials will be fetched from flask app's config for connection. |
| 48 | + mail.init_app(app) |
| 49 | + msg = Message(subject=title, sender=sender, body=body, recipients=recipients) |
| 50 | + with app.open_resource("requirements.txt") as fp: |
| 51 | + # Demonstration of attaching a file to the mail |
| 52 | + msg.attach("requirements.txt", "requirements/txt", fp.read()) |
| 53 | + mail.send(msg) |
| 54 | + |
| 55 | + return {"message": "E-mail Alert Sent"}, 200 |
| 56 | + |
| 57 | + |
0 commit comments