Delivery Notifications in .NET MailMessage

If you ever need to get delivery reports when you send emails from within .NET – here is a nice code snippet which does it. I used this approach to stamp emails with a “Mail-CustomData” header which contained information leading back to a database entity. I then watched the mailReplyToAddress with a small program I wrote and updated the database when the message was received, or failed to deliver.

            MailMessage message = new MailMessage();
            message.From = new MailAddress("");
            message.ReplyToList.Add(new MailAddress(mailReplyToAddress));
            message.Headers.Add("Disposition-Notification-To", mailReplyToAddress);

            message.To.Add(new MailAddress(emailAddress));
            message.IsBodyHtml = true;
            message.Priority = MailPriority.High;
            message.Body = "This is the message.";
            message.Subject = "Mail Message With Delivery Reports";

            message.Headers.Add("Mail-CustomData", "1203495Dflgrk3012");

            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.Delay;

            System.Net.Mail.SmtpClient client = new SmtpClient();