Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions postmark/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ def to_json_message(self):

return json_message

def send(self, test=None):
def send(self, test=None, return_json=None):
'''
Send the email through the Postmark system.
Pass test=True to just print out the resulting
Expand Down Expand Up @@ -537,6 +537,21 @@ def send(self, test=None):
else:
endpoint_url = __POSTMARK_URL__ + 'email'

"""
Args:
return_json (bool | None):
True -> return parsed JSON
False -> return True/False
None -> fallback to settings.POSTMARK_RETURN_JSON (default False)
"""

if return_json is None:
try:
from django.conf import settings as django_settings
return_json = getattr(django_settings, "POSTMARK_RETURN_JSON", False)
except ImportError:
return_json = False

# Set up the url Request
req = Request(
endpoint_url,
Expand All @@ -556,8 +571,9 @@ def send(self, test=None):
jsontxt = result.read().decode('utf8')
result.close()
if result.code == 200:
self.message_id = json.loads(jsontxt).get('MessageID', None)
return True
parsed = json.loads(jsontxt)
self.message_id = parsed.get("MessageID", None)
return parsed if return_json else True
else:
raise PMMailSendException('Return code %d: %s' % (result.code, result.msg))
except HTTPError as err:
Expand Down Expand Up @@ -676,7 +692,7 @@ def _check_values(self):

message._check_values()

def send(self, test=None):
def send(self, test=None, return_json=None):
# Has one of the messages caused an inactive recipient error?
inactive_recipient = False

Expand All @@ -691,6 +707,21 @@ def send(self, test=None):
except ImportError:
pass

"""
Args:
return_json (bool | None):
True -> return parsed JSON
False -> return True/False
None -> fallback to settings.POSTMARK_RETURN_JSON (default False)
"""

if return_json is None:
try:
from django.conf import settings as django_settings
return_json = getattr(django_settings, "POSTMARK_RETURN_JSON", False)
except ImportError:
return_json = False

# Split up into groups of 500 messages for sending
for messages in _chunks(self.messages, PMBatchMail.MAX_MESSAGES):
json_message = []
Expand Down Expand Up @@ -729,6 +760,7 @@ def send(self, test=None):
results = json.loads(jsontxt)
for i, res in enumerate(results):
self.__messages[i].message_id = res.get("MessageID", None)
return results if return_json else True
else:
raise PMMailSendException('Return code %d: %s' % (result.code, result.msg))
except HTTPError as err:
Expand Down
76 changes: 76 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

import mock

import django
from unittest.mock import patch, MagicMock

from postmark import (
PMBatchMail, PMMail, PMMailInactiveRecipientException,
PMMailUnprocessableEntityException, PMMailServerErrorException,
Expand All @@ -29,6 +32,79 @@
from django.conf import settings


if not settings.configured:
settings.configure(
POSTMARK_TRACK_OPENS=False,
POSTMARK_API_KEY="dummy",
POSTMARK_SENDER="test@example.com",
)
django.setup()
Comment thread
nicholasserra marked this conversation as resolved.
Outdated

def make_fake_response(payload, code=200):
"""Helper to fake an HTTP response object."""
mock = MagicMock()
mock.code = code
mock.read.return_value = json.dumps(payload).encode("utf-8")
mock.close.return_value = None
return mock

@patch("postmark.core.urlopen")
def test_mail_returns_result(mock_urlopen):
# Fake Postmark single send response
Comment thread
nicholasserra marked this conversation as resolved.
Outdated
fake_payload = {
"To": "receiver@example.com",
"SubmittedAt": "2025-09-18T10:00:00Z",
"MessageID": "abc-123",
"ErrorCode": 0,
"Message": "OK"
}
mock_urlopen.return_value = make_fake_response(fake_payload)

mail = PMMail(
api_key="test-api-key",
sender="sender@example.com",
to="receiver@example.com",
subject="Hello",
text_body="Testing single mail return",
)
result = mail.send()

assert isinstance(result, dict)
assert result["ErrorCode"] == 0
assert result["Message"] == "OK"


@patch("postmark.core.urlopen")
def test_batch_mail_returns_results(mock_urlopen):
Comment thread
nicholasserra marked this conversation as resolved.
Outdated
# Fake batch response
fake_payload = [
{
"To": "receiver@example.com",
"SubmittedAt": "2025-09-18T10:00:00Z",
"MessageID": "abc-123",
"ErrorCode": 0,
"Message": "OK",
}
]
mock_urlopen.return_value = make_fake_response(fake_payload)

# Build PMMail objects
message = PMMail(
api_key="test-api-key",
sender="sender@example.com",
to="receiver@example.com",
subject="Hello",
text_body="Testing batch return",
)

# Pass list of PMMail objects to PMBatchMail
batch = PMBatchMail(api_key="test-api-key", messages=[message])
results = batch.send()

assert isinstance(results, list)
assert results[0]["ErrorCode"] == 0


class PMMailTests(unittest.TestCase):
def test_406_error_inactive_recipient(self):
json_payload = BytesIO()
Expand Down
Loading