Warm tip: This article is reproduced from stackoverflow.com, please click
excel outlook vba

How to add JPG file to oft template at specific location in on email body

发布于 2020-04-04 10:12:19

I'm trying to distribute emails via using outlook oft template. On the oft template at specific location i want to attached jpg file which i have created from excel range.

Dim OutApp As Object
Dim OutMail As Object
Dim str_jpeg_file as String
str_jpeg_file  = "B:\temp\test.jpg"
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItemFromTemplate(ThisWorkbook.Path & "\Test.oft")
With OutMail
    .To = "test@abcd.com"
    .CC = ""
    .BCC = ""
    .Subject = "Test mail"
    .SentOnBehalfOfName = "zyz@abcd"
    .Attachments.Add str_jpeg_file, 1, 0
    .HTMLBody = Replace(.HTMLBody, "##IMAGE_PLACEHOLDER##", "<img src=""cid:test.jpg""height=520 width=750>")
    '.Send
    .display
End With

Edit:

jpg file path updated i.e. str_jpeg_file

Questioner
1S1a4m9
Viewed
41
Pᴇʜ 2020-01-31 21:57

To give you a full working example:

Option Explicit

Sub test()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim str_jpeg_file As String
    str_jpeg_file = "C:\Temp\test.png"
    Set OutApp = CreateObject("Outlook.Application")
    'Set OutMail = OutApp.CreateItemFromTemplate(ThisWorkbook.Path & "\Test.oft")
    'instead of a template I create a new mail
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .To = "test@abcd.com"
        .CC = ""
        .BCC = ""
        .Subject = "Test mail"
        .SentOnBehalfOfName = "zyz@abcd"
        .Attachments.Add str_jpeg_file, 1, 0
        'first we write some placeholder text so we can replace it
        .HTMLBody = "lalala ##IMAGE_PLACEHOLDER## lala"

        'replace
        .HTMLBody = Replace(.HTMLBody, "##IMAGE_PLACEHOLDER##", "<img src=""cid:test.png""height=256 width=256>")
        '.Send
        .display
    End With
End Sub

Note that I used a new email (no template) because it is easier to show here.

And it works perfectly:

enter image description here

So if it doesn't work for you either your image file is no valid image or you did something else wrong like typos etc. or your template is somehow the issue. Check again with the code above.