Skip to content

Commit 4ea8415

Browse files
committed
fix attachments
1 parent 7ae02fc commit 4ea8415

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

src/postmarker/models/emails.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,42 @@ def prepare_attachments(attachment):
3838
}
3939
if len(attachment) == 4:
4040
result["ContentID"] = attachment[3]
41+
elif isinstance(attachment, EmailMessage):
42+
# Handle EmailMessage objects (from email.message module)
43+
# These can come from Django's message.message() or deconstruct_multipart
44+
payload = attachment.get_payload(decode=True)
45+
if payload is None:
46+
# For multipart or string payloads
47+
payload = attachment.get_payload()
48+
if isinstance(payload, bytes):
49+
content = b64encode(payload).decode()
50+
elif isinstance(payload, str):
51+
content = b64encode(payload.encode('utf-8')).decode()
52+
else:
53+
# For multipart messages, serialize the entire message
54+
content = b64encode(attachment.as_bytes()).decode()
55+
56+
content_type = attachment.get_content_type()
57+
filename = attachment.get_filename()
58+
if filename is None:
59+
# Generate filename based on content type
60+
if content_type == "message/rfc822":
61+
filename = "message.eml"
62+
else:
63+
filename = "attachment.txt"
64+
65+
result = {
66+
"Name": filename,
67+
"Content": content,
68+
"ContentType": content_type,
69+
}
70+
content_id = attachment.get("Content-ID")
71+
if content_id:
72+
if content_id.startswith("<") and content_id.endswith(">"):
73+
content_id = content_id[1:-1]
74+
if (attachment.get("Content-Disposition") or "").startswith("inline"):
75+
content_id = "cid:%s" % content_id
76+
result["ContentID"] = content_id
4177
elif isinstance(attachment, MIMEBase):
4278
payload = attachment.get_payload()
4379
content_type = attachment.get_content_type()

0 commit comments

Comments
 (0)