'Embed picture in outlook mail body excel vba
I am trying to embed a range from a worksheet as an image in outlook mail body. It's saving the picture correctly but I only see blank image in the outlook mail body. What am I doing wrong here?
Sub View_Email()
tName = Trim(MAIN.Range("tEmail"))
If Not tName Like "*@*.*" Then MsgBox "Invalid Email address": Exit Sub
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
'File path/name of the gif file
Fname = ThisWorkbook.Path & "\Claims.jpg"
Set oCht = Charts.Add
STAT.Range("A3:G26").CopyPicture xlScreen, xlBitmap
With oCht
.Paste
.Export Filename:=Fname, Filtername:="JPG"
'.Delete
End With
On Error Resume Next
With OutMail
.To = tName
.CC = ""
.BCC = ""
.Subject = STAT.Range("C1").Value
.HTMLBody = "<html><p>Summary of Claim Status.</p>" & _
"<img src=" & Fname & "' height=520 width=750>"
.display
'.Send 'or use .Display
End With
On Error GoTo 0
'Delete the gif file
'Kill Fname
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Solution 1:[1]
You need to add the image and hide it. The position 0
will add and hide it.
.Attachments.Add Fname, 1, 0
The 1
is the Outlook Constant olByValue
Once you add the image then you have to use "cid:FILENAME.jpg"
as shown below.
Try this
With OutMail
.To = tName
.CC = ""
.BCC = ""
.Subject = STAT.Range("C1").Value
.Attachments.Add Fname, 1, 0
.HTMLBody = "<html><p>Summary of Claim Status.</p>" & _
"<img src=""cid:Claims.jpg""height=520 width=750>"
.Display
End With
Screenshot
Solution 2:[2]
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. PR_ATTACH_CONTENT_ID
corresponds to the Content-ID
MIME header when the message is sent.
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>"
Keep in mind that setting content-id is preferable to using the attachment file name in the <img>
element since it would need to be properly encoded and (if I remember correctly) some e-mail clients have a problem with just using the attachment file name for images.
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 | |
Solution 2 | Dmitry Streblechenko |