Search code examples
pythonoutlookhtml-emailpywin32office-automation

HTML email body with embedded local image


I was trying to automate a email sending process. This email was supposed to have a image on its body. In the code below, I've put the image on the email html body. Since the image path is at my local machine, the recipients would not receive it on the email body, and it would only appear in the case that the email was sent to myself. Anyone here would know how to fix this issue?

import win32com.client as win32

outlook = win32.Dispatch('outlook.application')

mail = outlook.CreateItem(0)

recipients = 'example@gmail.com'

cropped_image = r'C:\\Users\\Antonio_Ravazzolo\\PycharmProjects\\AutomationDFS\\cropped_screenshot.png'

mail.To = recipients
mail.Subject = 'subject'
mail.HTMLBody = r'<img src="C:\\Users\\Antonio_Ravazzolo\\PycharmProjects\\AutomationDFS\\cropped_screenshot.png">'\
                '<p>Feel free to contact me in case you have any questions/doubts.<p>'\
                '<p>Regards, Antônio Ravazzolo.<p>'


mail.Send()

Solution

  • You need to set the PR_ATTACH_CONTENT_ID MAPI property (DASL name "http://schemas.microsoft.com/mapi/proptag/0x3712001F") using Attachment.PropertyAccessor.SetProperty and refer that attachment through the src attribute that matches the value of PR_ATTACH_CONTENT_ID set on the attachment:

    attachment = MailItem.Attachments.Add("c:\temp\MyPicture.jpg")
    attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1")
    MailItem.HTMLBody = "<html><body>Test image <img src=""cid:MyId1""></body></html>"