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

Scan for Emails with Attachments and Save Attachments to Files

Scan for emails with attachments and save attachments.

Chilkat Perl Downloads

Perl
use strict;
use warnings;
use Chilkat2;

# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.

my $imap = Chilkat2::Imap->new;

# Connect to an IMAP server.
# Use TLS
$imap->Ssl(1);
$imap->Port(993);
my $success = $imap->Connect('imap.example.com');
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

# Login
$success = $imap->Login('myLogin', 'myPassword');
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

# Select an IMAP mailbox
$success = $imap->SelectMailbox('Inbox');
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

# We can choose to fetch UIDs or sequence numbers.
my $fetchUids = 1;

# Get the message IDs of all the emails in the mailbox
my $messageSet = Chilkat2::MessageSet->new;
$success = $imap->QueryMbx('ALL', $fetchUids, $messageSet);
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

# Fetch the email headers into a bundle object:
my $bundle = Chilkat2::EmailBundle->new;
my $headersOnly = 1;
$success = $imap->FetchMsgSet($headersOnly, $messageSet, $bundle);
if (!$success) {
    print $imap->LastErrorText, "\n";
    exit;
}

# Scan for emails with attachments, and save the attachments
# to a sub-directory.
my $fullEmail = Chilkat2::Email->new;
my $emailHeader = Chilkat2::Email->new;
my $i = 0;
while ($i < $bundle->MessageCount) {
    # The bundle contains email headers..
    $bundle->EmailAt($i, $emailHeader);

    # Does this email have attachments?
    # Use GetMailNumAttach because the attachments
    # are not actually in the email object because
    # we only downloaded headers.
    my $numAttach = $imap->GetMailNumAttach($emailHeader);

    if ($numAttach > 0) {
        # Download the entire email and save the
        # attachments. (Remember, we
        # need to download the entire email because
        # only the headers were previously downloaded.

        # The ckx-imap-uid header field is added when
        # headers are downloaded.  This makes it possible
        # to get the UID from the email object.
        my $uidStr = $emailHeader->GetHeaderField('ckx-imap-uid');
        my $uid = int($uidStr);

        $success = $imap->FetchEmail(0, $uid, 1, $fullEmail);
        if (!$success) {
            print $imap->LastErrorText, "\n";
            exit;
        }

        $success = $fullEmail->SaveAllAttachments('attachmentsDir');

        for my $j (0 .. $numAttach - 1) {
            my $filename = $imap->GetMailAttachFilename($emailHeader, $j);
            print $filename, "\n";
        }
    }

    $i = $i + 1;
}

# Disconnect from the IMAP server.
$success = $imap->Disconnect();