Sunday, July 24, 2011

Send E-Mail using ASP.NET

Team, I got involved in a project where we need to send e-mail from ASP.NET web application.

Tried many techniques and got all these errors .


"Mailbox unavailable. The server response was: DY-001 (SNT0-MC4-F22) Unfortunately, messages from 76.175.219.250 weren't sent. Please contact your Internet service provider. You can tell them that Hotmail does not relay dynamically-assigned IP ranges. You can also refer your provider to http://mail.live.com/mail/troubleshooting.aspx#errors."
 "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first"

"Mailbox unavailable. The server response was: 5.7.3 Requested action aborted; user not authenticated"
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

After few research here is the final working code.

public static bool SendMessage()
{
            bool togoValue = false;
            try
            {
                MailMessage mm = new MailMessage();
                mm.Sender = new MailAddress("fromEmailID@hotmail.com");
                mm.From = new MailAddress("fromEmailID@hotmail.com ");
                mm.To.Add(new MailAddress( "toEmailID@hotmail.com "));
                mm.Subject = "This is test Subject";
                mm.Body = "This is test Body";
                SmtpClient client = new SmtpClient("smtp.live.com");
                client.Credentials = new NetworkCredential("fromEmailID@hotmail.com", "password");
                client.Port = 25;
                client.EnableSsl = true;
                client.Send(mm);
                togoValue = true;
            }
            catch (Exception ex)
            {
                throw new Exception("Error when sending mail." + ex.ToString());
            }
            return togoValue;
 }

Replace your values in the right location and give it a try.

I tried both GMail server (smtp.gmail.com) and Hotmail Server (smtp.live.com) and both are working fine.

Have fun coding !

All Blogs so far ...