Often web application needs to implement mail features for user verification, notification or to implement as trivial functionality as contact form. If your web host does not provide mail server then you can use external solution like mailgun
which provides push email functionality along with other useful features using Rest API
. It also provides free 10, 000 emails per month before charging you for the service. Learn how you can implement this with python and flask. Previously we have built contact form with flask and ReCaptcha. We will further develop contact form in this tutorial by adding email support.
Background
Our contact form is very simple to build and collect user name, email and message. It also validates submission using Google ReCaptcha API.
Configuring API endpoint and API Key
When you sign up in mailgun and add your domain you get API Endpoint URL where you send post requests and API Secret Key to authorize API calls made by you. You can either configure these variables in application configuration settings or configure in specific function which is making API calls.
API key and Token from mailgun would look something like below.
apikey = "key-abc123456pqr456xYz"
url = "https://api.mailgun.net/vN/domainAbcdefg.mailgun.org"
Send Mail API call with Requests
To make HTTPS
post request at url endpoint we would use python requests
library. You can install it with pip
pip install requests
Sending Mail
We assume that you have already collected details from user form submission. Beow code will deliver those details via HTTP Post request which will result delivery of mail. Note that every collected detail should be of type string
.
import requests
apikey = "key-abc123456pqr456xYz"
url = "https://api.mailgun.net/vN/domainAbcdefg.mailgun.org"
requests.post(url,
auth=("api", apikey),
data={"from": collected_email,
"to": ["you@example.com", "somebody-else@example.com"],
"subject": "New Contact Entry",
"text":collected_message}
)
Alternatively you can send html email by replacing text
with html
in data payload.
requests.post(url,
auth=("api", apikey),
data={"from": collected_email,
"to": ["you@example.com", "somebody-else@example.com"],
"subject": "New Contact Entry",
"html":html_message}
)
Note that if you are sending HTML Mail then first escape message collected by user to avoid potential security breach.