Skip to content
Open
Changes from 2 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
59 changes: 52 additions & 7 deletions src/postmarker/models/emails.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
from base64 import b64encode
from email.header import decode_header
from email.message import EmailMessage
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Expand Down Expand Up @@ -37,6 +38,42 @@ def prepare_attachments(attachment):
}
if len(attachment) == 4:
result["ContentID"] = attachment[3]
elif isinstance(attachment, EmailMessage):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was leaning towards just doing

elif isinstance(attachment, MIMEBase) or isinstance(attachment,EmailMessage):
   ....

and it worked but this is suposedly more comprehensive and does not assume all attachments are already base64 encoded

# Handle EmailMessage objects (from email.message module)
# These can come from Django's message.message() or deconstruct_multipart
payload = attachment.get_payload(decode=True)
if payload is None:
# For multipart or string payloads
payload = attachment.get_payload()
if isinstance(payload, bytes):
content = b64encode(payload).decode()
elif isinstance(payload, str):
content = b64encode(payload.encode('utf-8')).decode()
else:
# For multipart messages, serialize the entire message
content = b64encode(attachment.as_bytes()).decode()

content_type = attachment.get_content_type()
filename = attachment.get_filename()
if filename is None:
# Generate filename based on content type
if content_type == "message/rfc822":
filename = "message.eml"
else:
filename = "attachment.txt"

result = {
"Name": filename,
"Content": content,
"ContentType": content_type,
}
content_id = attachment.get("Content-ID")
if content_id:
if content_id.startswith("<") and content_id.endswith(">"):
content_id = content_id[1:-1]
if (attachment.get("Content-Disposition") or "").startswith("inline"):
content_id = "cid:%s" % content_id
result["ContentID"] = content_id
elif isinstance(attachment, MIMEBase):
payload = attachment.get_payload()
content_type = attachment.get_content_type()
Expand Down Expand Up @@ -76,15 +113,23 @@ def deconstruct_multipart_recursive(seen, text, html, attachments, message):
if message in seen:
return
seen.add(message)
if isinstance(message, MIMEMultipart):
if message.is_multipart():
for part in message.walk():
deconstruct_multipart_recursive(seen, text, html, attachments, part)
else:
content_type = message.get_content_type()
if content_type == "text/plain" and not text:
text.append(message.get_payload(decode=True).decode("utf8"))
# Use get_content() for EmailMessage, fall back to get_payload for MIME
if isinstance(message, EmailMessage):
text.append(message.get_content())
else:
text.append(message.get_payload(decode=True).decode("utf8"))
elif content_type == "text/html" and not html:
html.append(message.get_payload(decode=True).decode("utf8"))
# Use get_content() for EmailMessage, fall back to get_payload for MIME
if isinstance(message, EmailMessage):
html.append(message.get_content())
else:
html.append(message.get_payload(decode=True).decode("utf8"))
else:
# Ignore underlying messages inside `message/rfc822` payload, because the message itself will be passed
# as an attachment
Expand Down Expand Up @@ -285,7 +330,7 @@ def _construct_email(self, email, **extra):
"""Converts incoming data to properly structured dictionary."""
if isinstance(email, dict):
email = Email(manager=self._manager, **email)
elif isinstance(email, (MIMEText, MIMEMultipart)):
elif isinstance(email, (EmailMessage, MIMEText, MIMEMultipart)):
email = Email.from_mime(email, self._manager)
elif not isinstance(email, Email):
raise ValueError
Expand Down Expand Up @@ -348,7 +393,7 @@ def send(
):
"""Sends a single email.

:param message: :py:class:`Email` or ``email.mime.text.MIMEText`` instance.
:param message: :py:class:`Email`, ``email.message.EmailMessage``, or ``email.mime.text.MIMEText`` instance.
:param str From: The sender email address.
:param To: Recipient's email address.
Multiple recipients could be specified as a list or string with comma separated values.
Expand Down Expand Up @@ -391,10 +436,10 @@ def send(
Attachments=Attachments,
MessageStream=MessageStream,
)
elif isinstance(message, (MIMEText, MIMEMultipart)):
elif isinstance(message, (EmailMessage, MIMEText, MIMEMultipart)):
message = Email.from_mime(message, self)
elif not isinstance(message, Email):
raise TypeError("message should be either Email or MIMEText or MIMEMultipart instance")
raise TypeError("message should be either Email, EmailMessage, MIMEText or MIMEMultipart instance")
return message.send()

def send_with_template(
Expand Down