Sample code for 30+ languages & platforms
PowerShell 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 PowerShell Downloads

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

$original = New-Object Chilkat.Email
$success = $original.LoadEml("with-attachments.eml")
if ($success -ne $true) {
    $($original.LastErrorText)
    exit
}

$reply = New-Object Chilkat.Email
$success = $original.ToReply($reply)
if ($success -ne $true) {
    $($original.LastErrorText)
    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 -eq "") {
    $destination = $original.From
}

$success = $reply.AddMultipleTo($destination)
if ($success -ne $true) {
    $($reply.LastErrorText)
    exit
}

#  Link this answer to its parent and preserve the earlier conversation references.
$parentId = $original.GetHeaderField("Message-ID")
if ($parentId -ne "") {
    $reply.AddHeaderField("In-Reply-To",$parentId)
    $refs = New-Object Chilkat.StringBuilder
    $refs.Append($original.GetHeaderField("References"))
    if ($refs.Length -gt 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 -lt 1) {
    $("Reply has no destination. Review the original sender headers.")
    exit
}

$("Reply goes to: " + $reply.GetToAddr(0))
$("In-Reply-To: " + $reply.GetHeaderField("In-Reply-To"))

$success = $reply.SaveEml("reply.eml")
if ($success -ne $true) {
    $($reply.LastErrorText)
    exit
}

$("Saved reply.eml.")