Perl - Outlook - Including an embedded image into body of email (HTML)

376 Views Asked by At

I need to include an image into body of email (using HTML formatting) so it's embedded, not as an extra attachement using library Win32::OLE in Perl invoking the Outlook client installed on Windows.

Below code works, but received email does not display the image. I can see the only a small square symbol indicating the inline embedded image is missing or is corrupted .

#use strict;
use warnings;
use Win32::OLE;

#get new Outlook instance
my $mail = new Win32::OLE('Outlook.Application');
die "Unable to start Outlook instance: $!" if !defined $mail;

my $item = $mail->CreateItem(0);
die "Unable to create mail item: $!" if !defined $item;

$item->{'To'} = '[email protected]'; 
$item->{'CC'} = '';
$item->{'Subject'} = 'Test for embedded/inline image';
$item->{'BodyFormat'} = 'olFormatHTML'; 
$item->{'HTMLBody'} = "<html><body><img src=\"signature.png\"></body></html>";
$item->save();

#attach an image and make it embedded.
my $attachments = $item->Attachments();
$attachments->Add('C:\signature.png', olEmbeddeditem);

#send it
$item->Send();

my $error = Win32::OLE->LastError();
print STDERR "Win32::OLE error: $error" if $error;

Does anybody know what is wrong with the above code? Any advices are highly appreciated.

1

There are 1 best solutions below

2
On

You need to attach an image and then set a CID which you can use in the message body:

Attachment attachment = newMail.Attachments.Add(@"E:\Pictures\image001.jpg"
    , OlAttachmentType.olEmbeddeditem , null , "Some image display name" );

   string imageCid = "image001.jpg@123";

   attachment.PropertyAccessor.SetProperty(
     "http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageCid);

   newMail.HTMLBody = String.Format("<body><img src=\"cid:{0}\"></body>", imageCid );