Skip to main content

How to Send Emails in ASP.NET using C#

How to Send Emails in ASP.NET using C#

Notes:

  • import System.Net.Mail and System.Net packages on the top of the page.

  • I have written a customised static method which can be directly called by class name anywhere in the project.

  • The method SendMail takes 4 parameters. First parameter is body/content of the mail. Second parameter is Subject of the mail. Third parameter is To Email ID. Fourth parameter is From Email ID.

  • The method SendMail returns true if mail is sent or false if mail is not sent.

  • Steps to find Incoming Mail Server(SMTP).

  • Step-1.

  • Step-2.

  • Step-3.

  • Step-4.

using System.Net.Mail;
using System.Net;
public static bool SendMail(string body, string subject, MailAddress to, MailAddress from)
{
try
{
//give Incoming Mail Server(SMTP) as host name.
SmtpClient smtp = new SmtpClient("secure214.sgcpanel.com", 587);// or SmtpClient smtp = new SmtpClient("exchangesrv.xyz.com", 25);
smtp.EnableSsl = false;
smtp.Port = 25;//or 587/467/587;
smtp.Host = "secure214.sgcpanel.com";// or "smtp.gmail.com"; or "exchangesrv.xyz.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("rakesh@gmail.com", "Password");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage message = new MailMessage(from, to);
message.Body = body;
message.Subject = subject;
smtp.Send(message);
}
catch (Exception ex)
{
throw ex;
}
return true;
}

Comments