Perl Requires Chilkat v11.0.0+
Perl
Reply to an email and preserve its thread
See more Email Object Examples
Create a reply to with-attachments.eml. Address it to Reply-To when supplied, or to the original author otherwise. Link the reply to the original Message-ID, replace its body with a short answer, and print the destination before saving the draft.
Chilkat Perl Downloads
use strict;
use warnings;
use Chilkat2;
# Assumes Chilkat is unlocked. See Global Unlock Sample.
my $original = Chilkat2::Email->new;
my $success = $original->LoadEml('with-attachments.eml');
if (!$success) {
print $original->LastErrorText, "\n";
exit;
}
my $reply = Chilkat2::Email->new;
$success = $original->ToReply($reply);
if (!$success) {
print $original->LastErrorText, "\n";
exit;
}
$reply->From('Alex Rivera <alex@example.net>');
# This is a reply to the author, not a reply-all. Set the destination explicitly.
$reply->ClearTo();
$reply->ClearCC();
$reply->ClearBcc();
my $destination = $original->GetHeaderField('Reply-To');
if ($destination eq '') {
$destination = $original->From;
}
$success = $reply->AddMultipleTo($destination);
if (!$success) {
print $reply->LastErrorText, "\n";
exit;
}
# Link this answer to its parent and preserve the earlier conversation references.
my $parentId = $original->GetHeaderField('Message-ID');
if ($parentId ne '') {
$reply->AddHeaderField('In-Reply-To', $parentId);
my $refs = Chilkat2::StringBuilder->new;
$refs->Append($original->GetHeaderField('References'));
if ($refs->Length > 0) {
$refs->Append(' ');
}
$refs->Append($parentId);
$reply->AddHeaderField('References', $refs->GetAsString());
}
# A short text reply has no use for the original inline artwork or nested correspondence.
$reply->RemoveAttachedMessages();
$reply->RemoveHtmlAlternative();
$reply->DropRelatedItems();
$reply->SetTextBody('Thank you for your message.', 'text/plain');
if ($reply->NumTo < 1) {
print "Reply has no destination. Review the original sender headers.\n";
exit;
}
print 'Reply goes to: ', $reply->GetToAddr(0), "\n";
print 'In-Reply-To: ', $reply->GetHeaderField('In-Reply-To'), "\n";
$success = $reply->SaveEml('reply.eml');
if (!$success) {
print $reply->LastErrorText, "\n";
exit;
}
print "Saved reply.eml.\n";