Sending Email Using C# System.Net.Mail



Sending emails programmatically is a common requirement in various applications, whether for notifications, confirmations, or error reports. In this article, we'll explore how to send emails using C# by leveraging the System.Net.Mail namespace.

Prerequisites

Before diving into the code, ensure you have the following:

1. A valid email account (e.g., Gmail, Outlook) for sending emails.

2. SMTP (Simple Mail Transfer Protocol) server details, including:

  • SMTP server address (e.g., smtp.gmail.com for Gmail).
  • Port number (e.g., 587 for Gmail with TLS).
  • Sender's email and password.

Example Code

Here’s how you can create a C# function to send emails:

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

class EmailSender
{
    public static void SendEmail(string recipient, string subject, string body)
    {
        try
        {
            // Define the sender's email and credentials
            string senderEmail = "your_email@gmail.com";
            string senderPassword = "your_password"; // Use app password if using Gmail

            // Configure the SMTP client
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com")
            {
                Port = 587, // Use 465 for SSL or 587 for TLS
                Credentials = new NetworkCredential(senderEmail, senderPassword),
                EnableSsl = true
            };

            // Create the email message
            MailMessage mail = new MailMessage
            {
                From = new MailAddress(senderEmail),
                Subject = subject,
                Body = body,
                IsBodyHtml = true // Set to true if the body contains HTML
            };

            // Add recipient(s)
            mail.To.Add(recipient);

            // Send the email
            smtpClient.Send(mail);
            Console.WriteLine("Email sent successfully to " + toEmail);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to send email: " + ex.Message);
        }
    }

    static void Main(string[] args)
    {
        // Example usage
        string recipient = "recipient_email@example.com";
        string subject = "Test Email";
        string body = "<h1>Hello!</h1><p>This is a test email sent from a C# application.</p>";

        SendEmail(recipient, subject, body);
    }
}

Explanation

1. SMTP Configuration:

  • smtp.gmail.com: The SMTP server address for Gmail.
  • Port 587: The port for TLS-encrypted connections.
  • EnableSsl = true: Ensures the connection is secure.

2. Email Message:

  • From: Specifies the sender's email address.
  • To: Adds the recipient's email address.
  • Subject and Body: Define the content of the email.
  • IsBodyHtml: Allows you to send HTML-formatted emails.

3. Error Handling:
  • The try-catch block ensures graceful error handling if email sending fails.

Security Considerations

If you're using Gmail, you might encounter issues due to security restrictions. Here's how to resolve them:

1. Use an App Password:

  • Go to your Google account settings.
  • Enable 2-Step Verification.
  • Generate an App Password and use it in place of your email password.

2. Enable Less Secure Apps (not recommended):
  • Enable access for less secure apps in your Google account settings. This option is deprecated for modern setups.

Advanced Features

Sending Attachments

You can enhance the function to include file attachments:

 mail.Attachments.Add(new Attachment("path_to_file"));


Adding CC and BCC

You can add CC and BCC recipients like this:

 mail.CC.Add("cc_email@example.com");
mail.Bcc.Add("bcc_email@example.com");

With the above code, you can easily send emails from your C# applications. This functionality is useful for automating notifications, error reporting, or any other email-based communication. Always ensure secure handling of credentials and consider using configuration files or environment variables to store sensitive information.
Previous Post Next Post

نموذج الاتصال