Created
November 9, 2017 10:34
-
-
Save scardine/7d361c080ae7756de5ff5c64ee604fca to your computer and use it in GitHub Desktop.
Use Postmark + requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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