Sending Email with SMTP Authentication in C# .NET

On my current C# .NET project, the user wants to have the application send an email if a new data is being inserted to the database. I search on the MSDN for class that will do this task and I found SmtpMail class.

Using SmtpMail is very simple, first you need to add a reference on your project. You can do this by right clicking on â€˜Referencesâ€™ and click â€˜Add Referencesâ€™. On â€˜.Netâ€™ tab find â€˜System.Web.dllâ€™ and add it to your project.

Now here is the simple code for sending email without SMTP authentication:

How I got an error message using that code, the error message is “Could not access ‘CDO.Message’ object”. Iâ€™m confused with this error message as it doesnâ€™t giving any detailed information. At first I thought that itâ€™s because I uninstall Outlook Express and doesnâ€™t have Microsoft Outlook installed â€“ a web page said that CDO are being used by Outlook, but itâ€™s not.

After replacing the try catch code above with this one below, I found out that I canâ€™t connect to the mail server although I already specify it correctly on SmtpMail.SmtpServer properties.

Post navigation

7 thoughts on “Sending Email with SMTP Authentication in C# .NET”

This code is very common used. You can also use it in combination with accessing a database. For example: you can generate an email newsletter based on email data stored in a database. Unfortunately, problems can occur: other mailservers and anti spam machines can see your mass mail as a spam bomb……there goes your nice formated marketing letter!!! ;)

creating newsletter need more complicated emailing code, as you need to set the email header to bulk so the mail server knows that you send the mail in bulk.

if your newsletter member is quite big then you need to send the email partially to you member, for example 60 emails per hour or so. this is to reduce the possibility your mail server blacklisted.

the code above is only simple emailing code, if you look at MSDN the example there is not working. it seems that SmtpMail.SmtpServer doesn’t really set the mail server, that is why the code at MSDN example can’t connect to the mail server.

Problem with that code is, it will wait until the receiver’s sever will pick up the mail when your server is calling – since this may take 2 – 3 seconds your app seems to hang, if its a desktop app; if its a webapp, your page rendering/loading will seem to hang.
Only solution is to make this an asynchron task:
Either by sending the mail in a background thread (by encapsulating the smtp-mail-setup stuff in a class), or use some of the fancy MVC features to accomplish it.
Regards,