Trigger Email using C# | .NET Developers


INTRODUCTION

Sending an email from Web Application or Web Services are quite a common practise nowadays. Few common practices like notifying users, triggering errors, sending an update, sending a detailed report, etc. So there are different ways and different languages to trigger email, but today I will try to explain and share the code how you can trigger mail using the C# programming language.

I will try creating a console application and try to write a common method that can trigger email and that method can be reused later.

Step 1: Create a New Console App(.NET Framework)




Step 2: Create a .cs Page



Step 3: Start Writing Code -



        So as you can see senderEmailID and senderPassword we are storing in Web.Config (App.Config) and will fetch using ConfigurationManager.AppSettings[""] so that the first layer of data hiding can be done.

Note: 
  • Library for ConfigurationManager: System.Configuration
  • Library for SmtpClient: System.Net.Mail
  • Library for UTF8Encoding: System.Text
Now I will show how to write the App.Config code -


Complete Code to trigger Email Service


        public bool SendEmail(string toEmail, string subject, string mailBody)
        {
            try
            {
                string senderEmailID = ConfigurationManager.AppSettings["EmailID"].ToString();
                string senderPassword = ConfigurationManager.AppSettings["Password"].ToString();

                SmtpClient sc = new SmtpClient("smtp.gmail.com", 587);
                sc.EnableSsl = true;
                sc.Timeout = 100000;
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;
                sc.UseDefaultCredentials = false;
                sc.Credentials = new NetworkCredential(senderEmailID, senderPassword);

                MailMessage mm = new MailMessage(senderEmailID, toEmail, subject, mailBody);
                mm.IsBodyHtml = true;
                mm.BodyEncoding = UTF8Encoding.UTF8;
                sc.Send(mm);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }



For any queries please comment below, I will try solving your queries.




Comments