c sharp

C# Send Email

An electronic message that is sent from a single individual or organization to another via the internet is known as an email. The ability to swiftly and effectively communicate the information, documents, photos, and other sorts of data makes it one of the most popular and commonly utilized ways of communication. The act of generating and transmitting an email message by programmatic means is referred to as sending an email in C#. The internal.NET Framework classes or other libraries can be used for this. Within this guide, we will showcase some C# code examples to deliver an email via the C# code.

Example 1: Send an Email

Let’s get started with the very first C# code example to demonstrate the use of the “SmtpClient” class to send an email via the code. The given C# code is a simple program that utilizes the SMTP server of Gmail to transmit the emails.

Let’s break down the code and its functionality in each step. First of all, we need to import all the necessary C# namespaces that are required to process this code properly and efficiently. These namespaces include “System”, “System.Net”, and “System.Net.Mail”. After defining the namespaces, the proper working of code starts. So, we define the “Test” class with the “main” method. Inside the “main” method, the program tries to send an email along with dealing with any possible errors; the email uses a try-catch section.

Within the “try” section, we create a MailMessage object “m” to represent the email message. It sets the sender’s email address, recipient’s email address, subject, and the body of the email via the “MailAddress” class. After this, we create a SmtpClient object “C” that is used to send the email via Gmail’s SMTP server. It sets the SMTP server address (“smtp.gmail.com”) and the port number (587 for TLS), and enables the SSL encryption (Secure Sockets Layer) for secure communication. We then set the required credentials to authenticate with Gmail’s SMTP server using the “NetworkCredential” class.

The username is “Aqsa Yasin” and the passcode is set to “Aqsa@823”. Make sure that the “NetworkCredential” constructor should take the actual Gmail email address and the corresponding password as parameters. Make sure to enable the SSL by assigning it with the “true” value.

Now, you should call the “send” method of the SmtpClient object, passing the MailMessage object “m” as a parameter to send the email. Assuming that the email is delivered, the program prints the “Email Successful!” message to the console. If there is an error, it will be caught in the catch block and the program will print the error message using the WriteLine() function of the “Console” class of C#. The output of this program is either “Email Successful!” assuming that the email is delivered, or it displays an error message if there are any issues with sending the email.

using System;
using System.Net;
using System.Net.Mail;
class Test {
  static void Main() {
    try {
        MailMessage m = new MailMessage();
        m.From = new MailAddress("[email protected]");
        m.To.Add(new MailAddress("[email protected]"));
        m.Subject = "Hello C# World!";
        m.Body = "Checking C# test Email.";
        SmtpClient C = new SmtpClient("smtp.gmail.com");
        C.Port = 587;
        C.Credentials = new NetworkCredential("Aqsa Yasin", "Aqsa@823");
        C.EnableSsl = true;
        C.Send(m);
        Console.WriteLine("Email Successful!");
        }
        catch (Exception ex)   {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

The output of the previous code displays “Email Successful!” at the console as displayed in the following illustration. Please note that in the provided code, the credentials that are used to authenticate Gmail’s SMTP server are test credentials and need to be replaced with a valid Gmail email address and the corresponding password for the code to work properly.

Additionally, using the hard-coded credentials in the code is not recommended for security reasons, and it’s better to use a more secure approach like reading the credentials from a configuration file or using the secure storage mechanisms.

The specific error message on the failure of the email varies depending on the nature of the problem such as incorrect credentials, network issues, or SMTP server configuration problems.

Example 2: Send an Email with Attachment

The provided C# code is a simple example of sending an email with an attachment using the Gmail SMTP server. It demonstrates how to create a “MailMessage” object, set the sender and recipient email addresses, add an attachment, configure the SMTP client, and then send the email. The code begins by importing the necessary namespaces for sending the emails (System.Net.Mail) and managing the network communication (System.Net).

The “Test” class contains a static “main” method. Inside the “main” method, a “try-catch” block is used to address all possible problems that can come up when sending emails. A “MailMessage” object “m” is created to represent the email. The “From” property is set to the sender’s email address and the “To” property is initialized with the recipient’s email. The subject and body of the email are set using the “Subject” and “Body” properties, respectively. An attachment is added to the email using the “Attachments.Add” method.

The file path of the attachment is specified as “C:\\Desktop\\file.txt” in this example. Be careful to substitute the correct path for the file that you want to attach. The “SmtpClient” object “C” is created which represents the SMTP (Simple Mail Transfer Protocol) client that is used to send the email. The “SmtpClient” is configured with the Gmail SMTP server address (“smtp.gmail.com”) and the port number (“587”). The Gmail server requires authentication, so the “Credentials” property is set to the sender’s email address and password.

The “EnableSsl” property is set to “true” to activate the encryption using SSL/TLS for a safe server connection. The email is sent using the “C.Send(m)” method where “m” is the “MailMessage” object that contains the email details. Upon a safe email delivery, the “Email sent successfully!” message is displayed. Otherwise, if an exception occurs during the process, the error message is caught in the “catch” block and the error details are printed to the console.

Make sure to replace the “[email protected]”, “[email protected]”, “username”, and “password” with the actual email addresses and login credentials for the sender’s Gmail account. Also, ensure that the attachment file path (“path” variable) points to a valid file on your computer.

using System;
using System.Net;
using System.Net.Mail;
class Test
{
    static void Main()
    {
        try
        {
            MailMessage m = new MailMessage();
            m.From = new MailAddress("[email protected]");
            m.To.Add(new MailAddress("[email protected]"));
            m.Subject = "Testing...";
            m.Body = "Sending a file.";
            string path = "C:\\Desktop\\file.txt";
            m.Attachments.Add(new Attachment(path));
            SmtpClient C = new SmtpClient("smtp.gmail.com");
            C.Port = 587;
            C.Credentials = new NetworkCredential("username", "password");
            C.EnableSsl = true;
            C.Send(m);
            Console.WriteLine("Email sent successfully!");
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
    }
}

If the email is sent successfully and there are no exceptions found in your code, the output is as follows:

Conclusion

Always adopt the best practices and think about utilizing the safe techniques like SSL/TLS for email transmission. Keep in mind that when employing the third-party libraries for delivering a mail in C#, you have to make sure that they are trustworthy and manage the data safely to safeguard the user information and avoid any misuse.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.