Search code examples
c#smtpclientmailmessage

How to set multiple DeliveryNotificationOptions for a single MailMessage?


I want to send notifications on:

  • Success
  • Failure
  • Delay

when I send my emails.

Unfortunately, it seems like the DeliveryNotificationOptions enumeration doesn't include an option to do all of these:

+---------------+----------------------------------------------------+
| Member Name   | Description                                        |
+---------------+----------------------------------------------------+
| Delay         | Notify if the delivery is delayed.                 |
+---------------+----------------------------------------------------+
| Never         | A notification should not be generated under       |
|               | any circumstances.                                 |
+---------------+----------------------------------------------------+
| None          | No notification information will be sent. The mail |
|               | server will utilize its configured behavior to     |
|               | determine whether it should generate a delivery    |
|               | notification.                                      |
+---------------+----------------------------------------------------+
| OnFailure     | Notify if the delivery is unsuccessful.            |
+---------------+----------------------------------------------------+
| OnSuccess     | Notify if the delivery is successful               |
+---------------+----------------------------------------------------+

I'm not able to set more than 1 options like this:

 Msg.DeliveryNotificationOptions += DeliveryNotificationOptions.Delay;

What other options are there?

The best that I can think of would be to extend MailMessage with an IEnumerable of DeliveryNotificationOptions but I'm not quite sure how I'd use it.

Is this a viable way of doing this?


Solution

  • The DeliveryNotificationOptions enumeration has the Flags attribute applied to it, which indicates you can combine the values together:

    var notifyOnFailureAndsuccess = 
        DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess
    

    Using your code above, it's only a slight modification to get it to work:

    Msg.DeliveryNotificationOptions |= DeliveryNotificationOptions.Delay;
    

    See this question for discussion on how Flags actually works and what effect it has on your code.