Skip to content

Instantly share code, notes, and snippets.

@xtornasol512
Last active October 20, 2022 03:55
Show Gist options
  • Save xtornasol512/1c5a6ac7354c9eb367020d0f8f7f2017 to your computer and use it in GitHub Desktop.
Save xtornasol512/1c5a6ac7354c9eb367020d0f8f7f2017 to your computer and use it in GitHub Desktop.
A useful mailgun wrapper to send emails via api
import requests
from os import getenv
class MailgunWrapper:
""" Principal mailgun app """
PRIV_KEY = getenv("MAILGUN_PRIV_KEY", "")
FROM_EMAIL = getenv("MAILGUN_FROM_EMAIL", "")
def __init__(self, *args, **kwargs):
""" Initialize mailgun """
self.url_messages = F'https://api.mailgun.net/v3/{getenv("MAILGUN_COMPANY_DOMAIN", "")}/messages'
self.AUTH = ("api", self.PRIV_KEY)
self.from_email = F"YOUR COMPANY NAME<{self.FROM_EMAIL}>"
if not self.PRIV_KEY and not self.FROM_EMAIL:
raise Exception("[MailgunWrapper ERROR] Missing env vars")
def send_email(self, subject, to_emails, msg, msg_html):
""" Send a email to given mails
subject = email subject
to_emails = list
msg = txt
msg_html = the html markup message
"""
if not isinstance(to_emails, list):
to_emails = [to_emails]
data = {
"from": self.from_email,
"subject": subject,
"to": to_emails,
"text": msg
}
# Adding html msg if send
if msg_html:
data.update({"html": msg_html})
try:
r = requests.post(self.url_messages, data=data, auth=self.AUTH)
if r.status_code == 200:
print("[MailgunWrapper] Email Sent Successful")
else:
print(F"[MailgunWrapper] Error Sending Email: {r.status_code}, {r.content}")
except Exception as e:
print(F"[MailgunWrapper] Error Sending Email {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment