Sunday, October 21, 2012

How to send email from asp.net? Basic C# code to send simple email


Sending email in asp.net is very useful and customizable too. The powerful classes help you compose and send email in minute! The glamour has always fascinated me, but more important is the frequent questions that are asked in asp.net related forums on sending email in asp.net using C# or vb.net. We can send email using some smtp server. And if this is not viable (sometimes we don't have smtp accounts!) we can use our own gmail account to send email (Thank you gmail!)
Take one example- Here goes the question that was asked in asp.net forum-

"can someone give me code how to send an e-mail from c# code
I am working with a company using Microsoft outlook for my mails.
I want to send mail only to 1 person, also please help me in identifying "smtp hostname"
"


Here goes the simple and helpful answer.
Visiting all above listed links you must have realized that sending email in asp.net is quite fun and useful too. In fact, a lot of customizations exist depending on your requirement. My suggestion is to do the basic email sending first. After that you can play with the classes and objects to perform more actions. Let me show you the basic email sending using c#.

  1. //sending basic mail in asp.net   
  2.     public void SendBasicMail()  
  3.     {  
  4.         //create new mailmessage object  
  5.         MailMessage message = new MailMessage(new MailAddress("sangam@test.com"), new MailAddress("anup@best.com"));  
  6.         message.Body = "Hi. This is test message.";  
  7.         message.Subject = "Test Message!";  
  8.         message.IsBodyHtml = false;  
  9.   
  10.         //create smtp client and send mail  
  11.         SmtpClient client = new SmtpClient("mail.mysmtpserver.com", 25);  
  12.         try  
  13.         {  
  14.             client.Send(message);  
  15.             lblError.Text = "Email sent successfully!";  
  16.             lblError.ForeColor = Color.Green;  
  17.         }  
  18.         catch (Exception ex)  
  19.         {  
  20.             lblError.Text = "Email could not be sent. " + ex.Message;  
  21.             lblError.ForeColor = Color.Red;  
  22.         }  
  23.     }  

This simple example will help you understand the basics of sending email in asp.net web application.
Now interested in sending email using our own gmail account? Here goes the coding by getchinna_sv (Thank you getchinna_sv! Yours sangam100).

  1. protected void sendMail()  
  2.    {  
  3.        string from = "me@gmail.com"//Replace this with your own correct Gmail Address  
  4.        string to = "you@gmail.com"//Replace this with the Email Address to whom you want to send the mail  
  5.        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();  
  6.        mail.To.Add(to);  
  7.        mail.From = new MailAddress(from, "One Ghost", System.Text.Encoding.UTF8);  
  8.        mail.Subject = "This is a test mail";  
  9.        mail.SubjectEncoding = System.Text.Encoding.UTF8;  
  10.        mail.Body = "This is Email Body Text";  
  11.        mail.BodyEncoding = System.Text.Encoding.UTF8;  
  12.        mail.IsBodyHtml = true;  
  13.        mail.Priority = MailPriority.High;  
  14.   
  15.        SmtpClient client = new SmtpClient();  
  16.        //Add the Creddentials- use your own email id and password  
  17.        client.Credentials = new System.Net.NetworkCredential(from, "Password");  
  18.        client.Port = 587; // Gmail works on this port  
  19.        client.Host = "smtp.gmail.com";  
  20.        client.EnableSsl = true//Gmail works on Server Secured Layer  
  21.        try  
  22.        {  
  23.            client.Send(mail);  
  24.        }  
  25.        catch (Exception ex)  
  26.        {  
  27.            Exception ex2 = ex;  
  28.            string errorMessage = string.Empty;  
  29.            while (ex2 != null)  
  30.            {  
  31.                errorMessage += ex2.ToString();  
  32.                ex2 = ex2.InnerException;  
  33.            }  
  34.            HttpContext.Current.Response.Write(errorMessage);  
  35.        } // end try   
  36.    }   

client.Credentials = new System.Net.NetworkCredential(from, "Password"); in this statement... write your gmail password.... from address should be a gmail address....

Hope this post will help. Thank you. Happy Programming!