简体   繁体   中英

How to embed an image into an Outlook email using VBA

Very closely related to Embed picture in outlook mail body excel vba

I'm trying to embed an image into an Outlook email.

I'm using the following code snippet, half of which has been stolen from the post above:

Sub PictureEmail()
    Dim outApp As New Outlook.Application
    Dim OutMail As Object
    Dim Attchmnt As String
    Dim Signature As String
    Dim WB As Workbook
    Set WB = ThisWorkbook
   Attchmnt = "C:\Users\Blah\Painted_Lady_Migration.jpg"


    Set OutMail = outApp.CreateItem(0)
    On Error Resume Next
    With OutMail
    .To = WB.Names("to").RefersToRange.Value2
    .CC = WB.Names("cc").RefersToRange.Value2
    .BCC = WB.Names("bcc").RefersToRange.Value2
    .Subject = WB.Names("Subject").RefersToRange.Value2
   .HTMLBody = "<img src=""cid:Painted_Lady_Migration.jpg""height=520 width=750>"
   .display
   End With

   If Attchmnt = "" Then
   Else
   OutMail.Attachments.Add Attchmnt
   End If

   On Error GoTo 0

End Sub

However, when looking at the generated email, I have the error "The linked image cannot be displayed. The file may have been moved, renamed, or deleted".

I've tried a few different ways to attach the file, including:

.HTMLBody = "<img src=" & Chr(34) & "cid:Painted_Lady_Migration.jpg" & Chr(34) & "height=520 width=750>"

I just can't get it to work >_<

I saw somewhere that spaces in the name/filepath can throw it, so I replaced the spaces in the name with underscores

What dumb thing am I forgetting/missing?

The cid is created when you attach it, so you need to do that before you display/send it.

Try it like this

Set OutMail = outApp.CreateItem(0)
With OutMail
    .To = WB.Names("to").RefersToRange.Value2
    .CC = WB.Names("cc").RefersToRange.Value2
    .BCC = WB.Names("bcc").RefersToRange.Value2
    .Subject = WB.Names("Subject").RefersToRange.Value2
    If Attchmnt <> "" Then 
       .Attachments.Add Attchmnt ' (additional arguments are optional)
       .HTMLBody = "<img src=""cid:Painted_Lady_Migration.jpg"" height=520 width=750>"
    Else
       .HTMLBody = "[no attachment included]"
    End If
   .Display
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM