OJ Develops

Thoughts on software development. .NET | C# | Azure

How to Send Email Using C#

05 August 2013

How to Send Email Using C# thumbnail

Sending email is a useful feature to have in many web applications. For instance, internet marketing strategies often involve using autoresponders to constantly send offers to subscribers. Daily reports can also be emailed to web administrators to keep them updated on the health of their site.

In this post, we will send a simple email using c sharp.

What Is Needed

In order to send email, we would need the following settings:

  1. The email host
  2. Credentials (username / password)

Of course, we would also need the email subject, body, From address, and To address.

Composing and Sending the Email

We would only need these classes to send email: SmtpClient, NetworkCredential, MailMessage, and MailAddress. We would have to include the namespaces System.Net and System.Net.Mail for us to use them.

Now it’s time to compose the email. Here’s where MailMessage and MailAddress come into play:

MailAddress fromAddress = new MailAddress("me@me.com");
MailAddress toAddress = new MailAddress("you@you.com");

MailMessage message = new MailMessage
{
    From = fromAddress,
    Subject = "hi, this is a test",
    Body = "<html><head></head><body><h1>Hello, world!</h1></body></html>",
    IsBodyHtml = true
};
message.To.Add(toAddress);

In the above code, we used the constructor of the MailAddress class that takes one argument, which is the name of the address. We then created the MailMessage using object initializer syntax.

Notice that the body is an html fragment, and a property called IsBodyHtml is set to true. Making the body an html document allows for the use of additional styles, such as colors, fonts, and layout.

Now that we have something to send, let’s send it using the SmtpClient and NetworkCredential classes:

SmtpClient smtpClient = new SmtpClient
{
    Host = "smtp.myHost.myDomain.com",
    Credentials = new NetworkCredential
    {
        UserName = "myUsername",
        Password = "myPassword"
    }
};
smtpClient.Send(message); // message is the MailMessage we created earlier

And that’s it! The email will be sent.