Send mail with VB.NET - and get notification if recipient couldn't be reached

· October 1, 2007

This has been a hard case to crack for quite sometime now… And it’s really annoying since at first the task seems so simple. Bare with me for a short history:

Very often users of a system want to send emails through the application, or send things in the application (document etc.) via email.

That is no biggie, i’ll use SMTP-mail - you think… until they add the demand “and of course we need to know if the mail reach the delivery adress”. Often that last part doesn’t come up until the system is in production and the situation occurrs.

Now you have some real tricky questions to handle. SMTP is a fire and forget protocol. There is no waiting until the mail has reached the recipient. Until .NET 2.0 that was also the case for us programmers. And of course you don’t want to integrated with Outlook or whatever the user is using on there machine.

In .NET 2.0 Microsoft has introduced some asynchronous stuff surrounding SMTP-mail sending, and some great SmtpExceptions. But i am not sure how it’s working in reality (see these links).

But today I’ve found a new, easy and quick solution to the problem: “Can you send mail with the application and please inform me if the recipient couldn’t be reached?”

The trick lies in a nice little enum on the MailMessage-class, DeliveryNotificationOptions. With this enum you can configure how notifications should be handled. All the notifications get send to the user that sent the email. Simple, yet brilliant.

Here are some example code that shows you how it works. Of course in my favorite language VB.NET:

' Create the messageDim message As New MailMessage ' This is adress that will get notifiedmessage.From = New MailAddress("")message.To.Add("")message.Subject = "Subject"message.Body = "The complete body of the mail"' Set DeliveryNotificationOptions.OnFailure to state that the From-adress' should be notified if the recipient couldn't be reachedmessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure' Create smtp-serviceDim smtpService As New Net.Mail.SmtpClient("")'Send the messagesmtpService.Send(message)

As i’ve told my project for some days now this problem is probably the one I’ve put in most effort on, in all my project, in total… and here is the solution.

Me so happy - me want to cry.

Twitter, Facebook