Consider these scenario in your newly developed Django Application:
What do you choose? Free Gmail Account to send email using python code? That is a nice idea provided you want to look unprofessional and you need not to send more than 500 emails per day.
But if you want professional look in your emails [from address something like admin@yourwebsite.com
instead of something@gmail.com
and do not want the limit on per day email count, then this article is for you.
smtp.gmail.com
.
First create a free account with Mailgun. You will get to choose the payment information while signing up. If you do not add payment info then you can send emails to verified recipients only.
After you are done with signup process, you can see your api key and other details in dashboard.
By default you are assigned a domain name to use while sending email which should look like as below:
sandbox2bb5d65ecfXXXXXXa32fXXXXXX93XXXa.mailgun.org
You will be able to see your domain information by clicking on domain link.
We will be using above details in our Django code to send sample email. Remember you can send email to verified recipients only from this default mailgun domain.
Add one of your email Id to verified recipients list. Similarly you can add your own domain in mailgun and verify that by following the process given in mailgun documentation. With a verified custom domain you can send email to anyone.
import requests def send_email(data): try: url = "https://api.mailgun.net/v3/YOUR-DOMAIN-NAME/messages" status = requests.post( url, auth=("api", "key-23bhxxxxxxx"), data={"from": "FROM-NAME <mailgun@sandbox2bxxxxxxxxxxxxxxx67xx.mailgun.org>", "to": "me@example.com"], "subject": "Test Email", "text": PLAIN-TEXT, "html": HTML-TEXT} ) return status except Exception as e: raise e
Replace the variables in CAPITAL LETTERS with actual value. PLAIN-TEXT
and HTML-TEXT
can be generated from template as below.
from django.utils.html import strip_tags from django.template import Context, Template from django.template.loader import get_template template = get_template("myapp/sample_template.html") context = Context(context_data) body_html = template.render(context_data) #HTML-TEXT body_text = strip_tags(body_html) #PLAIN-TEXT
If mail is accepted by Mailgun to send, you will receive 200 as status code.
if status.status_code == 200: # do something. update DB
So build Django app and send your first email.
Please comment if something is not working for you.