Email attachments

EmailContent.attachments is the collection of files attached to an email message. Each attachment exposes its name, content (bytes), and get_document_info(), and you can add and remove attachments.

Extract all attachments

from groupdocs.watermark import Watermarker
from groupdocs.watermark.options.email import EmailLoadOptions

def extract_attachments():
    with Watermarker("./message.msg", EmailLoadOptions()) as watermarker:
        content = watermarker.get_content()
        print("Attachments:", len(content.attachments))
        for attachment in content.attachments:
            info = attachment.get_document_info()
            print(f"- {attachment.name!r} type={info.file_type}")
            with open(f"./{attachment.name}", "wb") as f:
                f.write(attachment.content)

if __name__ == "__main__":
    extract_attachments()

message.msg is the sample file used in this example. Click here to download it.

Binary file (DOCX, 118 KB)

Download full output

Add an attachment

from groupdocs.watermark import Watermarker
from groupdocs.watermark.options.email import EmailLoadOptions

def add_attachment():
    with Watermarker("./message.msg", EmailLoadOptions()) as watermarker:
        content = watermarker.get_content()
        with open("./sample.docx", "rb") as f:
            data = f.read()
        content.attachments.add(data, "sample.docx")
        watermarker.save("./output.msg")

if __name__ == "__main__":
    add_attachment()

message.msg and sample.docx are the sample files used in this example. Download message.msg and sample.docx.

Binary file (MSG, 254 KB)

Download full output

Remove an attachment

The attachments collection supports remove_at(index) and remove(attachment). Iterate in reverse when removing by index:

from groupdocs.watermark import Watermarker
from groupdocs.watermark.options.email import EmailLoadOptions

def remove_attachment():
    with Watermarker("./message.msg", EmailLoadOptions()) as watermarker:
        content = watermarker.get_content()
        for i in range(len(content.attachments) - 1, -1, -1):
            if "sample" in content.attachments[i].name:
                content.attachments.remove_at(i)
        watermarker.save("./output.msg")

if __name__ == "__main__":
    remove_attachment()

message.msg is the sample file used in this example. Click here to download it.

Binary file (MSG, 12 KB)

Download full output

To watermark an attached document, open attachment.content in its own Watermarker (via io.BytesIO), add the watermark, and write the bytes back — the same pattern shown for spreadsheet attachments.

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.