Search code examples
excelvbaoutlookemail-attachments

Inserting Image to Email using VBA


I have the following snippet of VBA code ran in Excel which sends emails to our customers. I'm trying to insert a picture into the body of the email. The below code works fine when sending to my internal Outlook email, but does not work when sending to my personal Gmail account, meaning that the image does not show. Maybe because the LetterHead filepath is within our network? Help would be much appreciated!

Dim MItem As Outlook.MailItem
Dim LetterHead As String
LetterHead = "file path to .png file located in company network drive"

For x = 1 To xlList.DataBodyRange.Rows.Count
    Set MItem = OutlookApp.CreateItem(olMailItem)
    PolNum = xlList.DataBodyRange.Cells(x, 7).Value
    PolSubj = Subj & PolNum
    
    With MItem
        .To = EmailAddr
        .Subject = PolSubj
        .HTMLBody = "<center><img src=" & Chr(34) & LetterHead & Chr(34) & "></center>" & StrBody & .HTMLBody
        .Send
    End With

Solution

  • Maybe because the LetterHead filepath is within our network?

    Yes, you are on the right avenue. You need to upload the image to any web server to make it available for others. Be aware, email client application may block internet images automatically.

    If you need to make sure the image is displayed to a user you need to attach the image to the mail item (see Attachments.Add) and then set the PR_ATTACH_CONTENT_ID MAPI property (the DASL name is "http://schemas.microsoft.com/mapi/proptag/0x3712001F") using PropertyAccessor.SetProperty and refer to the attached file using the src attribute that matches the value of PR_ATTACH_CONTENT_ID property value set on the attachment object. For example:

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

    The PR_ATTACH_CONTENT_ID property corresponds to the Content-ID MIME header when the message is sent.