Send Mail in ASP.Net by using SmtpClient and MailMessage

If you want to send mails via your Gmail/outlook account from your ASP.Net web application, we can use SmtpClient and MailMessage.

Step-1
Create instance of MailMessage. Which contains details about mail that you want to send. It includes From, To, CC, BCC, Subject, Attachment, and Mail Body.

Step-2
Create instance of SmtpClient. In which we will store details of SMTP client such as Gmail/Outlook. We need to pass Host name in constructor. And set Credentials for loggin in that account. And also set Port no and SSL for that.

Step-3
Use Send() of SmtpClient and pass instance of MailMessage that we want to send.

string mail_host = "smtp.gmail.com";
string mail_from = "[email protected]";
string mail_password = "Your Password";
string mail_subject = "Send via .Net App";
string mail_body = "Text/Html content to send";
string mail_to = "[email protected]";

MailMessage mail = new MailMessage();
mail.From = new MailAddress(mail_from);
mail.To.Add(mail_to);
mail.Subject = mail_subject;
mail.Body = mail_body;
mail.IsBodyHtml = true;

SmtpClient SmtpServer = new SmtpClient(mail_host);
SmtpServer.Credentials = new System.Net.NetworkCredential(mail_from, mail_password);
SmtpServer.Port = 587;
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);

Note: MailMessage and SmtpClient both classes are defined with in System.Net.Mail namespace, so we must need to import it.

Leave a Reply

Your email address will not be published. Required fields are marked *