Jonathan Lam
Jonathan Lam

Reputation: 1330

How to embed an image in the body of an email using exchangelib library python

I need to embed multiple images into an email's body. I have tried below code but it does not embed it to the email's body. I am not looking to make it as an attachment

with open(i, 'rb') as f:
    my_logo = FileAttachment(
    name=i,
    content=f.read(),
    is_inline=True,
    content_type='GIF/Image',
    content_id=i,
)
m.attach(my_logo)

Thanks

Upvotes: 3

Views: 1256

Answers (1)

Erik Cederstrand
Erik Cederstrand

Reputation: 10220

Check out the example in the exchangelib documentation: https://ecederstrand.github.io/exchangelib/#attachments

In addition to creating the attachment, you need to reference it in your HTML body:

message = Message(...)
logo_filename = 'logo.png'
with open(logo_filename, 'rb') as f:
    my_logo = FileAttachment(
        name=logo_filename, content=f.read(),
        is_inline=True, content_id=logo_filename,
    )
message.attach(my_logo)
message.body = HTMLBody(
    '<html><body>Hello logo: <img src="cid:%s"></body></html>' % logo_filename
    )

Upvotes: 3

Related Questions