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

Swift

func chilkatTest() {
    var success: Bool = false

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

    let original = CkoEmail()!
    success = original.loadEml(mimePath: "with-attachments.eml")
    if success != true {
        print("\(original.lastErrorText!)")
        return
    }

    let reply = CkoEmail()!
    success = original.toReply(reply: reply)
    if success != true {
        print("\(original.lastErrorText!)")
        return
    }

    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()
    var destination: String? = original.getHeaderField(fieldName: "Reply-To")
    if destination == "" {
        destination = original.from
    }

    success = reply.addMultiple(to: destination)
    if success != true {
        print("\(reply.lastErrorText!)")
        return
    }

    //  Link this answer to its parent and preserve the earlier conversation references.
    var parentId: String? = original.getHeaderField(fieldName: "Message-ID")
    if parentId != "" {
        reply.addHeaderField(fieldName: "In-Reply-To", fieldValue: parentId)
        let refs = CkoStringBuilder()!
        refs.append(value: original.getHeaderField(fieldName: "References"))
        if refs.length.intValue > 0 {
            refs.append(value: " ")
        }

        refs.append(value: parentId)
        reply.addHeaderField(fieldName: "References", fieldValue: 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(bodyText: "Thank you for your message.", contentType: "text/plain")
    if reply.numTo.intValue < 1 {
        print("Reply has no destination. Review the original sender headers.")
        return
    }

    print("Reply goes to: \(reply.get(toAddr: 0)!)")
    print("In-Reply-To: \(reply.getHeaderField(fieldName: "In-Reply-To")!)")

    success = reply.saveEml(path: "reply.eml")
    if success != true {
        print("\(reply.lastErrorText!)")
        return
    }

    print("Saved reply.eml.")

}