How to send emails in C#?

How to send emails in C#?

How to send emails in C#?

Here you will learn how to send emails in C# using the .NET framework’s built-in classes.

We must use protocols to send or receive emails in C# or any other language.

 Email is a complex communication system that involves a client and a server. Email client sends or receive emails from different devices to email servers that store emails. By using a standardized protocol, email clients and servers can communicate with each other and ensure that emails are delivered correctly.

SMTP (Simple Mail Transfer Protocol) is used to send emails from a client to a server. It's a simple and reliable protocol that's widely supported by email service providers and servers.

IMAP and POP3 protocols are used for retrieving emails from an email server.

Here, we want to send emails so we only need to use the SMTP protocol. The following example sends an email using the SMTP protocol.

Example: Send Email in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;

namespace SizeOfOperator
{
    class Program
    {
        static void Main(string[] args)
        {

            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("[email protected]");
            mailMessage.To.Add("[email protected]");
            mailMessage.Subject = "Subject";
            mailMessage.Body = "This is test email";

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = "smtp.xdevspace.com";
            smtpClient.Port = 587;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential("username", "password");
            smtpClient.EnableSsl = true;

            try
            {
                smtpClient.Send(mailMessage);
                Console.WriteLine("Email Sent Successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

Let’s understand the above code step by step:

Step 1:

The System.Net.Mail namespace includes all the classes to send or receive emails. The System.Net namespace is used to provide network credentials. So, include them in your program.

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

step 2:

We need to construct an email message using the MailMessage class object. Provide the email details such as the sender, recipient, subject, and message body using the MailMessage object.

Example: Construct Email Message

MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("[email protected]");
mailMessage.To.Add("[email protected]");
mailMessage.Subject = "Subject";
mailMessage.Body = "This is test email";

Tip: Note that the From email should be your website’s email address from which you want to send emails.

Step 3:

Next, we need to configure the SMTP server details using the SmtpClient class.

Example: Configure SMTP Client

SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.xdevspace.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("username", " password");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;

step 4:

Finally, send the email using the Send() method of the SmtpClient class as smtpClient.Send(mailMessage);.

Thus, you can send emails using SMTP protocol in C#.

Send HTML Email

You can send email as an HTML page where you can use HTML tags in the body.

Example: HTML Body

message.IsBodyHtml = true;
message.Body = "<h1>Great offer</h1>";

Send Email Attachment

You can send an attachment in the email by adding the Attachment object in the MailMessage object, as shown below.

Example: Send Attachment

MailMessage message = new MailMessage();
mailMessage.From = new MailAddress("[email protected]");
mailMessage.To.Add("[email protected]");
mailMessage.Subject = "Subject";
mailMessage.Body = "This is test email with attachment.";

// Create a new Attachment object
Attachment attachment = new Attachment(@"C:\path\to\attachment.pdf");

//// Add the attachment to the MailMessage object
message.Attachments.Add(attachment);

smtpClient.Send(message);

Email Configuration in web.config

You can add the following configuration under the section in app.config or web.config. This will allow you to change the sender’s email address and credentials without modifying the code.

Example: SMTP Section in web.config

<system.net>
    <mailSettings>
    <smtp from=" [email protected] ">
    <network host="smtp.xdevspace.com"
                port="587"
                userName="username"
                password="password"
                enableSsl="true" />
		</smtp>
	</mailSettings>
</system.net>

Now, the following send email without hardcoded sender’s email credentials in the code.

Example: Send an Email

MailMessage message = new MailMessage();
message.To.Add(new MailAddress("[email protected]"));
message.Subject = "Subject";
message.Body = "This is test email.";

Attachment attachment = new Attachment(@"D:\logo.png");
message.Attachments.Add(attachment);

SmtpClient smtpClient = new SmtpClient();
smtp.Send(message);

Thus, you can send emails using the built-in SMTPClient class in C#. You can also use MailKit library to send and receive emails in .NET.

All Comments