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

Find and save an attachment and list inline images

See more Email Object Examples

Find an attachment by filename and media type, then save its decoded bytes to a path you choose. Enumerate inline resources separately to read their Content-IDs.

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('with-attachments.eml');
if (!$success) {
    print $email->LastErrorText, "\n";
    exit;
}

my $filename = Chilkat2::StringBuilder->new;
my $mediaType = Chilkat2::StringBuilder->new;
my $found = 0;
my $i = 0;
while ($i < $email->NumAttachments) {
    $filename->SetString($email->GetAttachmentFilename($i));
    $mediaType->SetString($email->GetAttachmentContentType($i));
    if (($filename->ContentsEqual('agenda.csv', 0)) && (($mediaType->ContentsEqual('text/csv', 0)) && (!$found))) {
        my $data = Chilkat2::BinData->new;
        $success = $email->GetAttachmentBd($i, $data);
        if (!$success) {
            print $email->LastErrorText, "\n";
            exit;
        }

        $success = $data->WriteFile('received-agenda.csv');
        if (!$success) {
            print "Failed: data.WriteFile.\n";
            exit;
        }

        print 'Saved attachment: ', $data->NumBytes, " bytes.\n";
        $found = 1;
    }

    $i = $i + 1;
}

if (!$found) {
    print "No matching attachment.\n";
}

$i = 0;
while ($i < $email->NumRelatedItems) {
    print 'Related: ', $email->GetRelatedContentType($i), '  Content-ID: ', $email->GetRelatedContentID($i), "\n";
    $i = $i + 1;
}