2

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()
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45

3 Answers3

1

You need to attach an image to the mail item and use the cid notation in the message to refer to the embedded image in the HTML markup.

mail.Attachments.Add "D:\ImageFile.img", olByValue, 0
sImgName = "ImageFile.img" 
mail.HTMLBody = "<img src='cid:" & sImgName & "'" & " ><br>" 

Otherwise, the local path make sense only to your machine:

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

There is no such path on the recipient, right? :)

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
1

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>"
Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78
0

The problem is you are the only person who accesses the image path, and on that path, you have an image. There is no path on other computers as if you pass it through the email in others computer. you can solve it by :

1- you can save the image in the static folder. (if you use the Flask or Django as backend)

2- or upload it on the cloud and give access from there.

3- pass the image on the attachment

Marya
  • 170
  • 1
  • 8