Search code examples
excelvbaoutlookhtml-email

How to embed pictures in an Outlook Email using Excel VBA?


I need to embed two pictures in the email body (it doesn't matter if I attach them too).

This code attaches, but it doesn't embed.

'Attach(0)' means full path of 1st pic
'Attach(1)' means full path of 2nd pic
'Temp(0) means "shortname1.jpg"
'Temp(1) means "shortname2.jpg"

Dim Temp(1) As String
Temp(0) = Replace(Attach(0), ruta & "\", "")
Temp(1) = Replace(Attach(1), ruta & "\", "")
Set MItem = OutlookApp.CreateItem(olMailItem)
With MItem
    .To = Email
    .CC = CopyEmail
    .Subject = Localidad & " " & "- Pay Period " & Format(Semana, "DD-MMM-YYYY") & " " & "Report"
    .Attachments.Add lnvo
    .Attachments.Add Attach(0), 1
    .Attachments.Add Attach(1), 1
    .HTMLBody = "<html><p>Charts</p>" & "<img src=""cid:" & Temp(0) & """height=520 width=750>" & "<img src=""cid:" & Temp(1) & """height=520 width=750>"
    .Body = Msg
    .Send
    '
End With

Solution

  • Based on @ChrisFNZ and @braX comments, going up and down, I removed '.Body' and I inserted the '.Body' Text in the 'HTMLBody' ('Msg' Variable).

    In the other hand, I decided to insert the double quotes in the Temp() variables. and it worked perfectly.

        Dim Temp(1) As String
        Temp(0) = Replace(Attach(0), ruta & "\", "") & """"
        Temp(1) = Replace(Attach(1), ruta & "\", "") & """"
        Set MItem = OutlookApp.CreateItem(olMailItem)
        With MItem
            .To = Email
            .CC = CopyEmail
            .Subject = Localidad & " " & "- Pay Period " & Format(Semana, "DD-MMM-YYYY") & " " & "Report"
            .Attachments.Add lnvo
            .Attachments.Add Attach(0), 1
            .Attachments.Add Attach(1), 1
            .HTMLBody = "<html><p" & Msg & "</p>" & "<img src=""cid:" & Temp(0) & " height=150 width=750>" & "<img src=""cid:" & Temp(1) & " height=150 width=750>"
            '.Body = Msg
            .Send
        End With
    

    Thanks everyone!