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

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

email = Chilkat::CkEmail.new()
success = email.LoadEml("message.eml")
if (success != true)
    print email.lastErrorText() + "\n";
    exit
end

fields = Chilkat::CkXml.new()
fields.put_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")
report = Chilkat::CkEmail.new()
success = email.ToDsn("The destination mailbox does not exist.",fields.getXml(),true,report)
if (success != true)
    print email.lastErrorText() + "\n";
    exit
end

report.put_From("Mail delivery agent <postmaster@example.net>")
#  RFC 3464 puts the reporting MTA in its own block, ahead of the recipient fields.
mimeBytes = Chilkat::CkBinData.new()
success = report.GetMimeBd(mimeBytes)
if (success != true)
    print report.lastErrorText() + "\n";
    exit
end

mime = Chilkat::CkMime.new()
success = mime.LoadMimeBd(mimeBytes)
if (success != true)
    print mime.lastErrorText() + "\n";
    exit
end

statusPart = Chilkat::CkMime.new()
success = mime.PartAt(1,statusPart)
if (success != true)
    print mime.lastErrorText() + "\n";
    exit
end

status = Chilkat::CkStringBuilder.new()
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)
    print mime.lastErrorText() + "\n";
    exit
end

print "Saved delivery-status.eml." + "\n";