blog

Home / DeveloperSection / Blogs / Send an email using 'Sysyem.Net.Mail' in C#

Send an email using 'Sysyem.Net.Mail' in C#

Send an email using 'Sysyem.Net.Mail' in C#

Ravi Vishwakarma 222 07-Jun-2024

You may ship emails with the usage of the System.Net.Mail namespace, which gives classes for building and sending emails. The number one instructions you'll paint with are SmtpClient and MailMessage. Below is a step-with the aid of-step manual on a way to ship emails in C#:

Step 1: Add Required Namespaces
Make sure to include the vital namespaces on the pinnacle of your code report:

using System; 
using System.Net; 
using System.Net.Mail; 

Step 2: Create and Configure the SmtpClient
The SmtpClient elegance is used to ship the e-mail through an SMTP server. You want to configure it with the SMTP server's deal and credentials.

Step 3: Create the MailMessage
The MailMessage magnificence represents the email you want to ship. It consists of residences like the sender, recipient, issue, and body.

Step 4: Send the Email
Use the Send method of SmtpClient to send the MailMessage.

Example Code
Here is an entire example that demonstrates how to send an email:

using System;
using System.Net;
using System.Net.Mail;

namespace ConsoleApplication1
{
    public class SendEmail
    {
        // Private constructor to prevent instantiation
        private SendEmail()
        {
            // TODO: Complete member initialization
        }

        // Method to set up the SMTP client for sending emails
        private SmtpClient SetUpEmailEngine()
        {
            // Set up the SmtpClient with the server details
            SmtpClient smtpClient = new SmtpClient("smtp.example.com")
            {
                Port = 587, // SMTP port number
                Credentials = new NetworkCredential("your_email@example.com", "your_password"), // SMTP server credentials
                EnableSsl = true // Enable SSL for secure connection
            };
            return smtpClient;
        }

        // Factory method to create an instance of SendEmail
        public static SendEmail Instance()
        {
            return new SendEmail();
        }

        // Static method to send an email
        public static bool Send(string RecepientEmail, string Subject, string MailBody)
        {
            try
            {
                // Create the MailMessage object with the necessary details
                MailMessage mailMessage = new MailMessage
                {
                    From = new MailAddress("your_email@example.com"), // Sender email address
                    Subject = Subject, // Email subject
                    Body = MailBody, // Email body
                    IsBodyHtml = true // Set to true if the body contains HTML
                };
            
                // Add recipient to the mail message
                mailMessage.To.Add(RecepientEmail);
                // You can add multiple recipients by repeating the above line with different email addresses

                // Send the email using the SMTP client
                Instance().SetUpEmailEngine().Send(mailMessage);

                Console.WriteLine("Email sent successfully.");
                return true;
            }
            catch (Exception ex)
            {
                // Handle any errors that occur when sending the email
                Console.WriteLine("Error sending email: " + ex.Message);
            }
            return false;
        }
    }

    // Main program class
    public class Program
    {
        public static void Main(string[] args)
        {
            // Send a test email
            SendEmail.Send("ravi.v@mindstick.com", "This is a test email", "I am just testing the email functionality");
            Console.ReadLine(); // Wait for user input to keep the console open
        }
    }
}

Explanation
SmtpClient Configuration:

  1. Replace "smtp.Example.Com" together with your SMTP server's cope with.
  2. Use the perfect port-wide variety (e.g., 587 for TLS/STARTTLS, 465 for SSL, 25 for non-steady).
  3. Provide the sender's e-mail and password in the NetworkCredential constructor.

MailMessage Setup:

  1. Set the From address to the sender's e-mail. 
  2. Set the Subject and Body of the e-mail. 
  3. Add recipients to the usage of the To. Add method. You can add a couple of recipients by way of calling this method more than one instance.
  4. Set IsBodyHtml to actual if the body of the e-mail contains HTML; in any other case, set it to fake.

Sending the Email:

  1. Call the Send approach of SmtpClient to ship the email. 
  2. Handle any exceptions to capture errors all through the sending procedure.

Security Note
Avoid hardcoding your electronic mail credentials for your source code. Instead, don't forget to use steady garage strategies inclusive of environment variables, encrypted configuration files, or steady secrets management services.

Additional Features

  1. Attachments: You can add attachments to the MailMessage for the usage of the Attachments belongings.
  2. CC/BCC: You can upload CC and BCC recipients using the CC and BCC properties of the MailMessage.
    Example with Attachment and CC
using System;
using System.Net;
using System.Net.Mail;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    /* 
    Provides functionality to send emails.
    */
    public class SendEmail
    {
        /* Private constructor to prevent instantiation */
        private SendEmail() { }

        /* Sets up the SMTP client for sending emails */
        private SmtpClient SetUpEmailEngine()
        {
            // Set up the SmtpClient with the server details
            SmtpClient smtpClient = new SmtpClient("smtp.example.com")
            {
                Port = 587, // SMTP port number
                Credentials = new NetworkCredential("your_email@example.com", "your_password"), // SMTP server credentials
                EnableSsl = true // Enable SSL for secure connection
            };
            return smtpClient;
        }

        /* Sets up the email message with sender, subject, and body */
        private MailMessage SetUpEmailMessage(string SenderEmail, string Subject, string MailBody)
        {
            // Create the MailMessage object with the necessary details
            MailMessage mailMessage = new MailMessage
            {
                From = new MailAddress(SenderEmail), // Sender email address
                Subject = Subject, // Email subject
                Body = MailBody, // Email body
                IsBodyHtml = true // Set to true if the body contains HTML
            };
            return mailMessage;
        }

        /* Factory method to create an instance of SendEmail */
        public static SendEmail Instance()
        {
            return new SendEmail();
        }

        /* Sends an email */
        public static bool Send(string SenderEmail, string RecipientEmail, string Subject, string MailBody)
        {
            try
            {
                var instance = Instance();
                var mailMessage = instance.SetUpEmailMessage(SenderEmail, Subject, MailBody);
                // Add recipient to the mail message
                mailMessage.To.Add(RecipientEmail);
                // You can add multiple recipients by repeating the above line with different email addresses

                // Send the email using the SMTP client
                instance.SetUpEmailEngine().Send(mailMessage);

                Console.WriteLine("Email sent successfully.");
                return true;
            }
            catch (Exception ex)
            {
                // Handle any errors that occur when sending the email
                Console.WriteLine("Error sending email: " + ex.Message);
            }
            return false;
        }

        /* 
        Sends an email with CC and attachment 
        */
        public static bool SendWithAttachment(string SenderEmail, string[] RecipientEmails, string Subject, string MailBody, string[] CCEmails = null, string[] BCCEmails = null, string[] AttachmentPaths = null)
        {
            try
            {
                var instance = Instance();
                var mailMessage = instance.SetUpEmailMessage(SenderEmail, Subject, MailBody);

                // Add recipients to the mail message
                foreach (string Email in RecipientEmails.Where(x => EmailVerification.IsValidEmail(x)))
                {
                    mailMessage.To.Add(Email);
                }

                // Add CC recipients
                if (CCEmails != null)
                {
                    foreach (string Email in CCEmails.Where(x => EmailVerification.IsValidEmail(x)))
                    {
                        mailMessage.CC.Add(Email);
                    }
                }

                // Add BCC recipients
                if (BCCEmails != null)
                {
                    foreach (string Email in BCCEmails.Where(x => EmailVerification.IsValidEmail(x)))
                    {
                        mailMessage.Bcc.Add(Email);
                    }
                }

 // Add attachments if (AttachmentPaths != null) { foreach (string Path in AttachmentPaths) { mailMessage.Attachments.Add(new Attachment(Path)); } } // Send the email using the SMTP client instance.SetUpEmailEngine().Send(mailMessage); Console.WriteLine("Email sent successfully."); return true; } catch (Exception ex) { // Handle any errors that occur when sending the email Console.WriteLine("Error sending email: " + ex.Message); } return false; } } /* Provides functionality to verify email addresses. */ public class EmailVerification { /* Validates an email address. */ public static bool IsValidEmail(string email) { // Regular expression pattern for validating email addresses string pattern = @"^[\w.+-]+@[\w-]+\.[\w.-]+$"; // Create a Regex object Regex regex = new Regex(pattern, RegexOptions.Multiline); // Use the IsMatch method to validate the email address return regex.IsMatch(email); } } // Main program class public class Program { public static void Main(string[] args) { // Send a test email //SendEmail.Send("mindstick_admin@mindstick.com", "ravi.v@mindstick.com", "This is a test email", "I am just testing the email functionality"); SendEmail.SendWithAttachment("mindstick_admin@mindstick.com", new string[] { "ravi.v@mindstick.com" }, "This is test", "This is test"); Console.ReadLine(); // Wait for user input to keep the console open } } } 

Explanation

SendEmail Class:

  • SetUpEmailEngine Method: This private method sets up the SmtpClient with the server details.
  • Send Method: Static method to send an email. It creates a MailMessage object with necessary details and sends the email using the SMTP client. It catches and handles any exceptions that occur during the process.
  • SendWithAttachment Method: Static method to send an email with CC, BCC, and attachments. It validates email addresses using the EmailVerification class. It handles multiple recipients, CC, BCC, and attachments similar to the Send method.

EmailVerification Class:

  • IsValidEmail Method: Validates email addresses using a regular expression pattern.

Program Class:

  • Main Method: Entry point of the application. It sends a test email and waits for user input to keep the console open.

Updated 07-Jun-2024
Hi, my self Ravi Vishwakarma. I have completed my studies at SPICBB Varanasi. now I completed MCA with 76% form Veer Bahadur Singh Purvanchal University Jaunpur. SWE @ MindStick | Software Engineer | Web Developer | .Net Developer | Web Developer | Backend Engineer | .NET Core Developer

Leave Comment

Comments

Liked By