Sending email in ASP.NET using SMTP configuration from web.config

Pardhu2020
Posted by Pardhu2020 under ASP.NET category on | Points: 40 | Views : 2812
In this code snippet, we are going to use following namespace

using System.Net.Mail;
Here is a simple snippet of how to send an email message from “xxxxx@xxxx.com” to multiple email recipients (note that the To a CC properties are collections and so can handle multiple address targets).

In the web.config file, please write below configuration.

<system.net>
<mailSettings>
<smtp from="xxxx@xxxxx.com">
<network host="smtp.sendgrid.net" port="587" userName="xxxxx@xxxxx.com" password="xxxxx"/>
</smtp>
</mailSettings>
</system.net>

In the ASP.NET code behind page, you will need to write following code in a method that will be called to send email.

SmtpClient cle = new SmtpClient();
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add("XXXXX@XXXXX.com");
mailMsg.CC.Add("XXXXX@XXXXX.com");
mailMsg.To.Add("XXXXX@XXXXX.com");
mailMsg.Subject = "task 3";
mailMsg.IsBodyHtml = true;
mailMsg.Body += "This is an automated notification of transaction details from Bergen County Golf System." + "<br />";
mailMsg.Body += "<br />";
mailMsg.Body += "-----------------------------------------------------" + "<br/>";
mailMsg.Body += "Order Summary" + "<br/>" + "<br/>";
cle.Send(mailMsg);

In the above code snippet, we have instantiated SmtpClient object that exists into the System.Net.Mail namespace. After that we have also instantiated MailMessage object.

Comments or Responses

Login to post response