---
title: "Send an email using 'Sysyem.Net.Mail' in C#"  
description: "you can send emails using the System.Net.Mail namespace, which provides classes for constructing and sending emails."  
author: "Ravi Vishwakarma"  
published: 2024-06-07  
updated: 2024-06-07  
canonical: https://www.mindstick.com/blog/304328/send-an-email-using-sysyem-dot-net-mail-in-c-sharp  
category: "c#"  
tags: ["c#", ".net"]  
reading_time: 7 minutes  

---

# Send an email using 'Sysyem.Net.Mail' in C#

You may ship emails with the usage of the System.Net.Mail namespace, which gives classes for building and [sending emails](https://answers.mindstick.com/qa/109539/how-to-restore-outlook-no-longer-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#](https://www.mindstick.com/interview/34186/how-can-you-send-html-emails-in-c-sharp):

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

```cs
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:

```cs
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](https://www.mindstick.com/forum/33476/pls-send-me-source-code-for-changing-passward-in-asp-dot-net-i-tried-so-much-from-google-but-its-not-workining). Instead, don't forget to use steady garage strategies inclusive of [environment variables](https://www.mindstick.com/forum/159994/how-to-set-up-and-use-environment-variables-in-a-node-js-application), encrypted [configuration files](https://www.mindstick.com/blog/570/introduction-to-configuration-files-in-c-sharp), or steady secrets management services.

## Additional Features

1. **Attachments:** You can [add attachments](https://answers.mindstick.com/qa/96435/can-you-paste-links-or-add-attachments-to-invitations) to the MailMessage for the usage of the Attachments belongings.
2. **CC/BCC:** You can upload [CC and BCC](https://answers.mindstick.com/qa/97235/what-do-cc-and-bcc-mean) recipients using the CC and BCC properties of the MailMessage.\ Example with Attachment and CC

```cs
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](https://www.mindstick.com/forum/12939/access-private-method-another-class-using-constructor-in-java) sets up the `SmtpClient` with the server details.
- **Send Method:** [Static method](https://www.mindstick.com/blog/440/creating-static-methods-in-c-sharp) 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](https://www.mindstick.com/articles/11909/java-regex-or-regular-expression-in-java) 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.

---

Original Source: https://www.mindstick.com/blog/304328/send-an-email-using-sysyem-dot-net-mail-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
