'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 = '[email protected]'
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 1:[1]
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
Solution 2:[2]
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? :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marya |
| Solution 2 | Eugene Astafiev |
