Monday, February 12, 2007

System.Net.Mail.SmtpClient How To Send User Name and Password?

In my line of stuff I do, I often need to send automated email messages from both my web and desktop (or service) applications.

On .NET 2.0 framework there is now a new namespace called System.Net.Mail, so we should all take advantage of it. So I started to work on it. One problem; most of SMTP servers we deal with require some type of credentials.

If you look at the MSDN docs for the SMTP class, the MSDN's description and example of how to do this is really poor in the document. I would say that 99% of the time, we just want to send a user name and password along with the SMTP traffic, and do not need to rely on default user credentials in the CredentialsCache. It took me a bit of efforts to find how to do this, but it is actually simple. Make sure to include the following namespaces first.

The following example also shows how I am using the Properties object to pull the Application configuration file information. Since SMTP config is something that needs change from time to time, it is best to store the information in a configuration file. The only sticky issue is of course, the password saved in plain text, but in my case it is a closed application so this isn't an issue for me, and even if that leaks, it is not an immediate threat.

using System.Net.Mail;
using System.Net;
using System.Security.Principal;


private void SendEmail(string subject, string body)
{
string smtpServer = Properties.Settings.Default.SMTPServerBlankIfDontWantEmail;
if ((smtpServer == null) (smtpServer == "")) return;
try
{
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress (Properties.Settings.Default.EmailTo));
msg.From =(new MailAddress(Properties.Settings.Default.EmailFrom));
msg.Body = body;
SmtpClient c = new SmtpClient(Properties.Settings.Default.SMTPServerBlankIfDontWantEmail,
Properties.Settings.Default.SMTPPort);
string token = "mmonitor";

c.Credentials = new NetworkCredential
(Properties.Settings.Default.SMTPUserName,
Properties.Settings.Default.SMTPPassword);


// c.SendAsync(msg, token); // Don't hang the rest of the stuff is SMTP hangs.
c.Send(msg);
this.toolStripStatusLabel2.Text = "Sent email";
}
catch (System.Exception ex)
{
this.toolStripStatusLabel2.Text = ex.Message;
}
}


No comments: