Sample code for 30+ languages & platforms
Perl Requires Chilkat v11.0.0+

Add an attachment and an inline image

See more Email Object Examples

Add a file attachment from memory and embed an image in the HTML body using its Content-ID. Start with any email that has an HTML body, or use text-and-html.eml from the preceding example. Save the result as with-attachments.eml.

Chilkat Perl Downloads

Perl
use strict;
use warnings;
use Chilkat2;

# Assumes Chilkat is unlocked. See Global Unlock Sample.

my $email = Chilkat2::Email->new;
my $success = $email->LoadEml('text-and-html.eml');
if (!$success) {
    print $email->LastErrorText, "\n";
    exit;
}

my $data = Chilkat2::BinData->new;
$success = $data->AppendString("Time,Activity\r\n09:00,Welcome\r\n10:00,Field session\r\n", 'utf-8');
if (!$success) {
    print "Failed: data.AppendString.\n";
    exit;
}

$success = $email->AddAttachmentBd('agenda.csv', $data, 'text/csv');
if (!$success) {
    print $email->LastErrorText, "\n";
    exit;
}

# AddRelatedBd returns the identifier that must appear after cid: in the HTML.
my $image = Chilkat2::BinData->new;
$success = $image->AppendEncoded('iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAASUlEQVR4nGMQK/ImBv3//x/CYCBSNQkaIKqJ1YCmGkUDsigu1egakOWwqsaiAaICl2p0P8DV4VKNxdP4VWMPJTyqiY04sZGuAQBhyhp6A/ap2AAAAABJRU5ErkJggg==', 'base64');
if (!$success) {
    print "Failed: image.AppendEncoded.\n";
    exit;
}

my $cid = $email->AddRelatedBd('confirmed.png', $image);
if (!$email->LastMethodSuccess) {
    print $email->LastErrorText, "\n";
    exit;
}

my $html = Chilkat2::StringBuilder->new;
$html->Append('<p><img alt=\'Confirmed\' src="cid:');
$html->Append($cid);
$html->Append('"></p>');
$html->Append($email->GetHtmlBody());
$success = $email->AddHtmlAlternativeBody($html->GetAsString());
if (!$success) {
    print $email->LastErrorText, "\n";
    exit;
}

$success = $email->SaveEml('with-attachments.eml');
if (!$success) {
    print $email->LastErrorText, "\n";
    exit;
}

print "Saved with-attachments.eml.\n";