Friday, 17 June 2016

C# Send email message with smtp settings in web.config file.

In C# we can we set email settings in web.config file. We just need to specify  from address info in the <system.net> section of the web.config file as below example.

Step 1: Paste this code in the web.config file
<system.net>
    <mailSettings>
      <smtp from="from@test.com">
        <network host="smtp.gmail.com" port="587" userName="from@test.com" password="password" enableSsl="true" />
      </smtp>
   </mailSettings>
  </system.net>

Step 2: Now you no need to set from email and password in the c# code. You just need to add following code.

public static void SendEmail(string to, string body, string subject)
        {
            MailMessage mail = new MailMessage();
            mail.To.Add(to);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Send(mail);
        }

No comments:

Post a Comment