Sending emails using C#

Name: *
My email: *
Recipient email: *
Message: *
Fields marked as bold are compulsory.
You haven't filled in compulsory values. The email is not correct

Everybody knows what an email is. You write an email body, set a subject, pick your recipient, press the Send button and your email is off. However there are emails that can be automatically generated. Most probably you are at times recieving commercial emails, emails asking you to confirm your email address does exist, a site administrator would get emails by visitors filling in some sort of contact form. All kind of spam mails are even created this way. There is no actual person writing such mails. The source code is ready and all the user has to do is to fill in the essential info. No google or windows live accout is required. However you need to have access to an smtp client. A simple web server will be no good.

 
email
 
 

Creating an email

We are going to create a simple method called SendEmailTo in order to send an email.  
 
public static bool SendEmailTo(string emailFrom, string emailTo, string emailSubject, string emailBody)
    {
        //Variable used to confirm successful sending to the caller method
        bool success = false;
        try
        {
            //Create the email
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(emailFrom);
            mail.To.Add(emailTo);
            mail.Subject = emailSubject;
            mail.Body = emailBody;
 
            //Create the smtp server
            SmtpClient smtp = new SmtpClient("MySMTPClient");
            smtp.Credentials = new System.Net.NetworkCredential("username", "password");
 
            //Send the email
            smtp.Send(mail);
            success = true;
        }
        catch (Exception ex)
        {
        }
 
        return success;
    }
 
First things first. To send an email we have to create an email. The MailMessage class can be found in the System.Net.Mail library. A MailMessage object has four basic attributes : from, to , subject and body.
 
  •  From contains the sender's address.
  •  To contains the recipient's address.
  •  Subject contains the mail subject.
  •  Body contains the mail body.
 
In the example we have used the simplest MailMessage constructor. Instead, we could have used the constructor containing all the previous elements.
 
public static bool SendEmailTo(string emailFrom, string emailTo, string emailSubject, string emailBody)
    {
        //Variable used to confirm successful sending to the caller method
        bool success = false;
        try
        {
            //Alternative constructor
            MailMessage altMail = new MailMessage(emailFrom, emailTo, emailSubject, emailBody);
 
            //Create the smtp server
            SmtpClient smtp = new SmtpClient("MySMTPClient");
            smtp.Credentials = new System.Net.NetworkCredential("username""password");
 
            //Send the email
            smtp.Send(mail);
            success = true;
        }
        catch (Exception ex)
        {
        }
 
        return success;
    }
 
 
An example of how we could call that method would be
bool emailConfirmation = SendEmailTo("randomMail@dotnethints.gr","admin@dotnethints.com",".NetHints email subject","This is the mail body!");
 
A MailMessage object can have more than one recipients. You will have to add them one by one.
mail.To.Add(emailTo);
 
An easy way to add multiple recipients is to create a string containing the addresses seperated by, let's say, a semicolon ("randomMail@dotnethints.gr;randomMail1@dotnethints.gr")
 
If so, we would then seperate the addresses using the following code
MailMessage mail = new MailMessage();
 
string[] emails = emailTo.Split(';');
foreach (string email in emails)
mail.To.Add(email);
 
One more thing concerning the MailMessage is its ability to be portrayed in html form. Most commercial emails contain fancy colors, images, css etc in order to attract the reader instead of pure text.
To accomplish this you have to set the IsBodyHtml attribute to true. Now, all you have to do is to insert html text in the Body attribute.
 
MailMessage has many attributes including CC, Bcc and Atachments. 
 
email
 

The SmtpClient

OK, so far we have created our email. Now we have to send it. Earlier I mentioned that to send an email you need an smtp server.
 
We will use the SmtpClient class located in the System.Net.Mail library. The SmtpClient has two key attributes: host and credentials.
 
Host is the name of your smtp host. They let you know what it is and you simply fill it in the code. The credentials refer to your smtp server credentials. So there's not much to do in order to set your SmtpClient. All you need is to get the host name and its credentials and you're done.
 
SmtpClient smtp = new SmtpClient("MySMTPClient");
smtp.Credentials = new System.Net.NetworkCredential("username""password");
 
Sometimes you may need to change the port your client is using. This can be set using the Port attribute. Default value is 25. The port number set to the smtp protocol.
 
You are now ready. Send your email.
smtp.Send(mail);
 
If something goes wrong you will get a System.Net.Mail.SmtpException. If not your email is sent. Congratulations!
 
 

Conclusion

Step by step we found out how to send an email using source code. What you need is to create a MailMessage and an SmtpClient. The MailMessage contains info such as the mail body and its recipients, while the SmtpClient contains info concerning your smtp host
 

Back to BlogPreviousNext

Comments


  • 08-04-2013, 00:14 AM
    kbadas
    Posts: 6
    Hello mate, so far I've been trying to cover issues concerning more "traditional" .Net issues, that seem to be more helpful than "modern" ones. However, since you asked I will schedule such an article for one of the following posts.
  • 30-03-2013, 16:42 PM
    Anon
    Posts: 1
    Any chance for a blog post on the new C# 5 features, async & await? Apparently Win8/modern only supports asynchronous APIs for file handling etc, so these features are becoming very important.

Leave a comment
Name: