It’s often handy to have your web site or application send emails. “Thanks for registering.” “Thanks for your order.” “Hey tech support, the web site is down.”
.NET 2.0 provides a few handy classes for outbound emails. Below is some code you can use in your ASP.NET application to send an email. Notice there is some authentication code you can use if your SMTP server requires a username and password in order to send emails. If you aren’t sure, try sending an email without a username or password. If you get an SmtpException with a 550 or 553 Relay denied error (SmtpException.StatusCode == SmtpStatusCode.ClientNotPermitted), then you’ll need to authenticate. 🙂
// create the message object System.Net.Mail.MailMessage myMessage = new System.Net.Mail.MailMessage(); myMessage.To[0] = "some.guy@hotmail.com"; myMessage.From = "some.girl@hotmail.com"; myMessage.Subject = "this is a test message"; myMessage.Body = "hello there!ntest message!"; // create the SmtpClient object. Specify the SMTP server in the Host property System.Net.Mail.SmtpClient mySMTPClient = new System.Net.Mail.SmtpClient(); mySMTPClient.Host = "smtpserver.emailfarm.com"; if (SMTP_SERVER_REQUIRES_AUTHENTICATION) { // create the NetworkCredential object with the username & password // to authenticate against the SMTP server System.Net.NetworkCredential myCredentials = new System.Net.NetworkCredential("username", "password"); mySMTPClient.UseDefaultCredentials = false; mySMTPClient.Credentials = myCredentials; } // send the message try { mySMTPClient.Send(myMessage); } catch (SmtpException e) { Response.Write(e.StatusCode); }
If you feel the need to email a file to someone, use code like the below
// Attach a file to the email message. // The second parameter is the content type (text, binary file, etc.) System.Net.Mail.Attachment myAttachment = new Attachment(strFilename, MediaTypeNames.Text.Plain); myMessage.Attachments.Add(myAttachment);
Lastly, you can send an email asynchronously via the SmtpClient.SendAsync(MailMessage, CallbackToken) method. You can attach an event handler to the SmtpClient.SendCompleted event to receive notification when your email has been sent. One big downer is you can only send one asynchronous email at a time — if you’re currently waiting for a previous SendAsync call to finish, other Send or SendAsync calls will fail. Which sortof sucks.
// Send an email without waiting for completion mySMTPClient.SendCompleted += new SendCompletedEventHandler(MyHandler); mySMTPClient.SendAsync(myMessage, null); void MyHandler(System.Object sender, AsyncCompletedEventArgs e) { // code goes here to say "sending complete!" or something }
Related links:
SmtpClient: http://msdn2.microsoft.com/en-us/library/4971yhhc(en-US,VS.80).aspx
SendAsync: http://msdn2.microsoft.com/en-us/library/x5x13z6h(en-US,VS.80).aspx
Attachment: http://msdn2.microsoft.com/en-us/library/e02kz1ak(en-US,VS.80).aspx