Detect and Process Bounced Emails

When sending emails, some messages may fail to reach their recipients, for example, due to an invalid recipient address or a full mailbox. These undelivered messages are known as bounced emails.

Aspose.Email for C++ provides a convenient way to detect and analyze bounced messages using the MailMessage and BounceResult classes. The MailMessage::CheckBounced() method determines whether a message is a bounce and returns a BounceResult object that contains detailed information such as:

  • Whether the message is bounced
  • The recipient address
  • The type of bounce action
  • The reason and status code of the bounce

This allows developers to automatically identify delivery failures and take appropriate action like cleaning invalid addresses from mailing lists.

The sections below show how to check a message, read the details of the failure and react to the reported action.

The Classes Involved

Class or method Purpose
MailMessage::CheckBounced Examines a MIME message and reports what it found
MapiMessage::CheckBounced The same for an Outlook item
BounceResult The outcome of the check
DSNAction The action the reporting server took

The samples in this article use these headers and namespaces:

#include <MailMessage.h>
#include <MailAddress.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <Mime/HeaderCollection.h>
#include <Bounce/BounceResult.h>
#include <Bounce/DSNAction.h>
#include <Mapi/MapiMessage.h>
#include <system/io/directory.h>
#include <system/io/path.h>
#include <system/object_ext.h>
#include <system/convert.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Bounce;
using namespace Aspose::Email::Mapi;

Check whether a Message Is a Bounce

CheckBounced always returns a BounceResult; IsBounced says whether the message really is a delivery notification.

SharedPtr<MailMessage> message = MailMessage::Load(u"failed1.msg");

SharedPtr<BounceResult> result = message->CheckBounced();

if (result->get_IsBounced())
{
    Console::WriteLine(u"This is a bounce message");
}

Read the Details of a Failure

A notification names the address that failed, a status code as defined by RFC 3463, the diagnostic text of the reporting server, and the action that was taken. The original message is included by some servers only, so check OriginalMessage for nullptr before using it.

SharedPtr<MailMessage> message = MailMessage::Load(u"failed1.msg");
SharedPtr<BounceResult> result = message->CheckBounced();

if (result->get_IsBounced())
{
    Console::WriteLine(u"Failed to: " + result->get_Recipient());
    Console::WriteLine(u"Status: " + result->get_Status());
    Console::WriteLine(u"Reason: " + result->get_Reason());
    Console::WriteLine(u"Action: " + ObjectExt::ToString(result->get_Action()));
}

// the original message is included in some notifications only
if (result->get_OriginalMessage() != nullptr)
{
    SharedPtr<MailMessage> original = result->get_OriginalMessage();
    Console::WriteLine(u"Original subject: " + original->get_Subject());
    Console::WriteLine(u"Original from: " + original->get_From()->get_Address());

    original->Save(u"OriginalMessage.eml", SaveOptions::get_DefaultEml());
}
else
{
    Console::WriteLine(u"The notification does not carry the original message");
}

For the sample above the library reports the recipient mmmmm@aspose.com, the status 5.1.1, the reason smtp;550 5.1.1 RESOLVER.ADR.RecipNotFound; not found and the action Failed.

React to the Reported Action

DSNAction distinguishes the situations that call for different handling:

Value Meaning What to do
Failed Delivery failed permanently Drop the address from the mailing list
Delayed Delivery postponed Retry later
Delivered Delivered successfully Nothing
Expanded The address expanded into several recipients Watch for further notifications
Relayed Passed to a system that does not report delivery Nothing
None No action named Investigate the message manually
SharedPtr<MailMessage> message = MailMessage::Load(u"failed1.msg");
SharedPtr<BounceResult> result = message->CheckBounced();

switch (result->get_Action())
{
case DSNAction::Failed:
    // permanent failure - drop the address from the mailing list
    Console::WriteLine(u"Delivery permanently failed for " + result->get_Recipient());
    break;

case DSNAction::Delayed:
    // temporary failure - put the address into a retry queue
    Console::WriteLine(u"Delivery delayed for " + result->get_Recipient());
    break;

case DSNAction::Delivered:
    Console::WriteLine(u"Successfully delivered");
    break;

case DSNAction::Expanded:
    Console::WriteLine(u"The address was expanded into several recipients");
    break;

case DSNAction::Relayed:
    Console::WriteLine(u"The message was relayed to a system that does not report delivery");
    break;

case DSNAction::None:
    Console::WriteLine(u"The notification does not name an action");
    break;
}

// a permanent failure whose status code starts with "5."
if (result->get_IsBounced() && result->get_Action() == DSNAction::Failed &&
    result->get_Status().StartsWith(u"5."))
{
    Console::WriteLine(u"Remove from the mailing list: " + result->get_Recipient());
}

Status Codes

The first digit of the status code separates the two groups that matter in practice.

Permanent failures - the address should not be tried again:

Code Meaning
5.1.1 The recipient does not exist
5.1.2 The domain does not exist
5.2.1 The mailbox is disabled
5.2.2 The mailbox is full
5.3.0 The message is too large
5.4.0 Routing error

Temporary failures - the message may go through on a later attempt:

Code Meaning
4.2.1 The mailbox is temporarily disabled
4.2.2 The mailbox is full
4.4.1 Connection timeout
4.4.2 Timeout while waiting for a connection
4.5.0 Temporary server error

Process a Folder of Notifications and Outlook Items

Bounces usually arrive in bulk, so they are processed in a loop. When the DSN part of a message does not name the failed address, the X-Failed-Recipients header often does. Outlook items are handled by the same CheckBounced method of MapiMessage.

// a folder of notifications
for (String file : IO::Directory::GetFiles(u"bounces"))
{
    SharedPtr<MailMessage> message = MailMessage::Load(file);
    SharedPtr<BounceResult> result = message->CheckBounced();

    if (result->get_IsBounced())
    {
        String recipient = result->get_Recipient();

        // some servers leave the recipient out of the DSN part
        if (String::IsNullOrEmpty(recipient))
        {
            recipient = message->get_Headers()->Get(u"X-Failed-Recipients");
        }

        Console::WriteLine(IO::Path::GetFileName(file) + u" -> " + recipient + u" (" + result->get_Status() + u")");
    }
}

// Outlook items are checked the same way
SharedPtr<MapiMessage> msg = MapiMessage::Load(u"failed.msg");
SharedPtr<BounceResult> mapiResult = msg->CheckBounced();
Console::WriteLine(u"MSG bounce detected: " + Convert::ToString(mapiResult->get_IsBounced()));

Mailboxes are read with the IMAP and POP3 clients of Aspose.Email for C++; every message they fetch is a MailMessage and can be passed to CheckBounced exactly as the files above.