Posted by & filed under ASP.NET.

Sending authenticated e-mails in .NET 2.0 — devel.oping.net:
ending e-mails in the .NET Framework 2.0 is about the same as in version 1.x. There are just a couple of variations. First, all the functionality is within the new System.Net.Mail namespace. The System.Web.Mail namespace, wich was used in the 1.x frameworks is now considered obsolete.

Lets get right to the code. It’s really straight forward and self explanatory:

 1 MailMessage oMsg = new MailMessage();
 2 
 3 // Set the message sender
 4 oMsg.From = new MailAddress(“xavier@devel.oping.net“, “Xavier Larrea“);
 5 
 6 // The .To property is a generic collection, 
 7 // so we can add as many recipients as we like.
 8 oMsg.To.Add(new MailAddress(“fox@foxcorp.org“,“John Doe“));
 9 
10 // Set the content
11 oMsg.Subject = “My First .NET email“;
12 oMsg.Body = “Test body - .NET Rocks!“;
13 oMsg.IsBodyHtml = true;
14 
15 SmtpClient oSmtp = new SmtpClient(“smtp.myserver.com“);
16 
17 //You can choose several delivery methods. 
18 //Here we will use direct network delivery.
19 oSmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
20 
21 //Some SMTP server will require that you first 
22 //authenticate against the server.
23 
24 NetworkCredential oCredential = new NetworkCredential(“myusername“,“mypassword“);
25 oSmtp.UseDefaultCredentials = false;
26 oSmtp.Credentials = oCredential;
27 
28 //Let’s send it already
29 oSmtp.Send(oMsg);

Very easy, right? Remember always to use the Try-Catch block when sending emails because lot of things can cause an exception: bad email addresses, authentication errors, network failure, etc.

I hope you find this code useful. Happy coding!

Comments are closed.