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

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 PHP Downloads

PHP
<?php

use Chilkat2\Email;
use Chilkat2\StringBuilder;

// Assumes Chilkat is unlocked. See Global Unlock Sample.

$original = new Email();
try {
    $original->LoadEml('with-attachments.eml');

    $reply = new Email();
    $original->ToReply($reply);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\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();
$destination = $original->GetHeaderField('Reply-To');
if ($destination === '') {
    $destination = $original->From;
}

try {
    $reply->AddMultipleTo($destination);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Link this answer to its parent and preserve the earlier conversation references.
$parentId = $original->GetHeaderField('Message-ID');
if ($parentId !== '') {
    $reply->AddHeaderField('In-Reply-To', $parentId);
    $refs = new StringBuilder();
    $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) {
    echo "Reply has no destination. Review the original sender headers.\n";
    exit;
}

echo 'Reply goes to: ', $reply->GetToAddr(0), "\n";
echo 'In-Reply-To: ', $reply->GetHeaderField('In-Reply-To'), "\n";

try {
    $reply->SaveEml('reply.eml');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo "Saved reply.eml.\n";