//
you're reading...

Uncategorized

Use MIME::Lite to create a multipart message with attachment

MIME::Lite is a great Perl module for working with MIME formatted email messages. However, one problem I ran into was trying to create a multipart message that has 1) a text version of the message 2) an HTML version of the message and 3) an HTML attachment. If I set the content type to “multipart/alternative” then the attachment showed up as part of the message but if I set the content type to “multipart/mixed” then the message showed up as an attachment. I couldn’t find a solution online so I figured it out on my own. Hopefully this helps someone in the future.

To get things right you have to create a multipart/alternative message that is nested within a multipart/mixed message. Here is the code I used:

my $html = “<html><body>This is the HTML message</body></html>”;
my $text = “This is the text message”;
my $attachment = “<html><body>This is the HTML attachment</body></html>”;
my $email = “someone@example.com”;

my $msg = MIME::Lite->new(
From        =>  ‘me@example.com’,
To          =>  $email,
Subject     =>  ‘Test message’,
Type        =>  ‘multipart/mixed’
);

my $part = MIME::Lite->new(
Type => ‘multipart/alternative’,
);
$part->attach(
Type => ‘text/html; charset=utf-8’,
Data => $html,
);
$part->attach(
Type => ‘text/plain’,
Data => $text,
);
$msg->attach($part);

$msg->attach(
Type => ‘text/html’,
Data => $attachment,
Filename => ‘filename.htm’,
Disposition => ‘attachment’
);

$msg->send;
if ( $msg->last_send_successful() ) {
print ”  Message sent to $email\n”;
} else {
print ”  Error sending email to $email\n”;
}

Be Sociable, Share!

Discussion

No comments yet.

Post a Comment