Main FAQ Category: General (9)
How to send HTML Email from ASP.NET 2.0 via server that requires SMTP Authentication?
Posted: 24-Mar-2008
Updated: 24-Mar-2008
Views: 4298

Here is an example on how to send email from ASPX page using a SMTP server that requires authentication:

Note: the code snippet assumes you have a Label component on Page with named lblMsg that will show
success/failure message to the user that is sending email.
(But this can be easily changed).

                SmtpClient client = new SmtpClient();
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = true;
                client.Host = "smtp.yourmailserver.com";
                client.Port = 25;
 
                // setup Smtp authentication
                System.Net.NetworkCredential credentials = 
                       new
System.Net.NetworkCredential("[email protected]", "yourpassword");
                client.UseDefaultCredentials = false;
                client.Credentials = credentials;                
 
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress("[email protected]");
                msg.To.Add(new MailAddress("[email protected]"));
 
                msg.Subject = "This is a test Email subject";
                msg.IsBodyHtml = true;
                msg.Body = string.Format("<html><head></head><body><b>Test HTML Email</b></body>");
 
                try
                {
                    client.Send(msg);
                    lblMsg.Text = "Your message has been successfully sent.";
                }
                catch (Exception ex)
                {
                    lblMsg.ForeColor = Color.Red;
                    lblMsg.Text = "Error occured while sending your message." + ex.Message;
                }