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

Create a delivery failure report

See more Email Object Examples

A delivery agent can report a failure for an actual envelope recipient. Supply its observed SMTP outcome and enhanced status code, and return only the original headers when that is sufficient. This example saves a report for inspection. DSN format.

Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat v11.4.0 or greater.
JavaScript
var success = false;

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

var email = new CkEmail();
success = email.LoadEml("message.eml");
if (success !== true) {
    console.log(email.LastErrorText);
    return;
}

var fields = new CkXml();
fields.Tag = "DeliveryStatusFields";
fields.NewChild2("Final-Recipient","rfc822; alex@example.net");
fields.NewChild2("Action","failed");
fields.NewChild2("Status","5.1.1");
fields.NewChild2("Diagnostic-Code","smtp; 550 5.1.1 Mailbox does not exist");
var report = new CkEmail();
success = email.ToDsn("The destination mailbox does not exist.",fields.GetXml(),true,report);
if (success !== true) {
    console.log(email.LastErrorText);
    return;
}

report.From = "Mail delivery agent <postmaster@example.net>";
//  RFC 3464 puts the reporting MTA in its own block, ahead of the recipient fields.
var mimeBytes = new CkBinData();
success = report.GetMimeBd(mimeBytes);
if (success !== true) {
    console.log(report.LastErrorText);
    return;
}

var mime = new CkMime();
success = mime.LoadMimeBd(mimeBytes);
if (success !== true) {
    console.log(mime.LastErrorText);
    return;
}

var statusPart = new CkMime();
success = mime.PartAt(1,statusPart);
if (success !== true) {
    console.log(mime.LastErrorText);
    return;
}

var status = new CkStringBuilder();
status.Append("Reporting-MTA: dns; mx.example.net\r\n\r\n");
status.Append(statusPart.GetBodyDecoded());
statusPart.SetBody(status.GetAsString());
success = mime.SaveMime("delivery-status.eml");
if (success !== true) {
    console.log(mime.LastErrorText);
    return;
}

console.log("Saved delivery-status.eml.");