C# – How to send emails – Sample Code

MiniBytes: In this article we are going to see, how to send emails using C# code. This tutorial will be helpful for you to send emails using C# code without any external libraries, which you can use in your C# WPF application, Form Application or Console Application. What i am narrating here is the code which was taken from the live projects which i am currently working on.

Microsoft has given us an inbuilt library “System.Net.Mail” to send emails to any of the users, if you know the email id, port number and smtp address.

The code below uses a simple inbuilt library class which can be use to send an smtp email using the port 25. This code uses no credentials to send the emails to the users, if you want use authenticated credentials to send emails to the users, then you need to set the username and password.

MailMessage mail = new MailMessage();
            SmtpClient client = new SmtpClient();
            client.Port = 25;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Host = "<mail server address>";
            mail.IsBodyHtml = true;        
            mail.To.Add(new MailAddress("<To Address 1>"));
            mail.To.Add(new MailAddress("<To Address 2>")); 
            mail.To.Add(new MailAddress("<To Address 3>"));
            mail.From = new MailAddress("<From Address>");
            mail.Subject = "Email Notification...!";
            string bodyTemplate = "<h1>Notification</h1><br/><p>Test</b>";
            mail.Body = bodyTemplate;

There is also a function which you can use to attach the files and send the body of message in HTML format.

If you want to send emails to more recipients, then you need to use loops in your code that will fetch the address and send to the users.

Enjoy the code…I you have any doubts please leave comment..Thank you…:-)..

You may also like...

Leave a Reply

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