Skip to content

Instantly share code, notes, and snippets.

@scardine
Created November 9, 2017 10:34
Show Gist options
  • Save scardine/be16c89e9d2bf691d77b6bf7ed88722a to your computer and use it in GitHub Desktop.
Save scardine/be16c89e9d2bf691d77b6bf7ed88722a to your computer and use it in GitHub Desktop.
Use Postmark + requests
import os
from base64 import b64encode
import requests
from django.conf import settings
from django.template.loader import render_to_string
import magic
try:
token = settings.POSTMARK_APIKEY
except AttributeError:
token = 'POSTMARK_API_TEST'
def sendmail(sender, recipient, subject, template_name, context, attachements=None):
data = {
"From": sender,
"To": recipient,
"Subject": subject,
"HtmlBody": render_to_string(template_name + '.html'),
"TextBody": render_to_string(template_name + '.txt'),
}
if attachements:
data["attachments"] = []
for file_obj in attachements:
if isinstance(file_obj, str): # Is this a path to a file?
with open(file_obj, 'rb') as input_file:
name = file_obj
content_type = magic.from_file(file_obj)
payload = b64encode(input_file.read())
else:
payload = b64encode(file_obj.read())
try:
name = file_obj.file.name # Django file
except AttributeError:
name = file_obj.name # Regular file?
file_obj.seek(0)
content_type = magic.from_buffer(file_obj.read(1024))
else:
content_type = magic.from_file(name)
data["attachments"].append({
"Name": os.path.basename(name),
"Content": payload,
"ContentType": content_type
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment