Sending Simple E-Mail in C#

It’s been decades since carrier pigeons became digitalized and supercharged. Nowadays sending a mail has become synonymous with sending an e-mail, meaning electronic mail, and usually this delivery process takes less than a second. As a result, we’re required to send e-mail nearly every day. This article takes a look at how we can accomplish this task in C#.

Thus, this is going to be a tutorial written in the “how-to” fashion. First, we are going to dwell on the basics and I’m going to explain the theory. This is where we’ll talk about frameworks, functions, libraries, and in short about SMTP servers. We’ll also discuss what credentials are and why are they important, as well as  SSL. Later on, we’re going to develop ready-to-run real-world applicable source code that sends mail.

Throughout this article I’m going to present three solutions to accomplish the task of sending mail using C#. The first will be based on the System.Web.Mail component that is part of the older dot net frameworks (.NET 1.0 and 1.1). If you are coding in those environments then this is going to be useful to you. Next we’ll also present the currently possible solution that is based on the latest .NET frameworks.

Here I’m talking about .NET 2.0 and 3.5 (3.x). We are going to use the following components: System.Net and System.Net.Mail. These are all part of the latest dot net Frameworks. At the end of the article you will be able to download the archived source code of this tiny little application. By this point everything should make sense and you’ll see the difference between the older solution and this one.

Ultimately, as the third solution, we’ll present the commercial component package called Chilkat, specifically their best-selling mail components: Chilkat Mail. We can use its 30-day trial period; that is more than enough time for us to play around and see how it performs, what we can do with it, and so forth. You’ll see a code sample that is based on Chilkat Mail, too. And that’s everything in a nutshell.

All of this being said, let’s get started.

{mospagebreak title=Theory}

Before we begin, let’s present what SMTP servers are all about. It is beyond the scope of this article to explain the history and the inner workings of SMTP servers. Thus, we’ll focus on just the absolutely necessary things and won’t bore you with extra details. SMTP stands for Simple Mail Transfer Protocol. It is the standard protocol, text-based, for e-mail transmissions over the Internet.

Our purpose is to send e-mails; therefore, we are going to work with SMTP servers. It makes sense, right? In our code we’re going to “compose” our message, add the necessary headers such as where it is coming from, where it is going, its subject, and the body of the mail. Right after all of this, we’re ready to send it toward the recipient. We need a free and public SMTP server to do this.

In our application we need to specify the address of the SMTP server through which our mail is supposed to go. Your program will contact the SMTP server, establish the connection, and then send the message along. There are more than a few free and public SMTP servers. For example, you can always use the one that your ISP supplies and maintains. Say your ISP is EarthLink, then it is at smtp.earthlink.com.

On the other hand, you can also use the massively popular Google’s SMTP server [Google Mail]. This is a bit trickier because they require network credentials, basically any valid GMail user account, to establish the connection with the server. Along with this, we also need to enable an SSL connection (encryption).

Google’s approach is safer because they do not allow connections from anonymous sources. As long as you supply a valid GMail username and password, you’re good; you log into your GMail account and send the e-mail through that source e-mail address. Regardless of the fields specified in your code, your Google account will become the source of the message that’s going to be sent. Plus, SSL is obviously safe.

On the other hand, there are numerous SMTP servers that allow connections from anybody; this includes anonymous sources. They do not require credentials (no username or password); neither do they offer SSL to encrypt the connection. Thus, they are often exploited by spammers to send out a massive amount of spam e-mail. Why is that? Because they accept anything as “source” of the mail, say jonny@bla.net.

As long as the spammer is behind a strong and non-transparent proxy to hide their IP address, then thousands if not millions of mails can be sent out through an SMTP server like this using a fake e-mail address. I’m not endorsing this; I’m mentioning it because it is useful to know what credentials are about and why some servers absolutely require these kinds of credentials. It all can be narrowed down to safety.

As a final note, these days, more often than not, the SMTP servers that are provided by ISPs are not requiring credentials; neither are those servers from “cheap” network hosting companies. A quick Google search on “free SMTP servers” turns up a huge list, out of which surely you can pick a few that are still valid.

Thankfully, there are pre-made libraries and components already included in the dot net Frameworks that can help us out during this e-mail sending task. We don’t need to write the transmissions functions, hand-shaking requirements, and lots of extra transaction stuff; we just rely on the functions that are readily available to us in .NET.

In the next section you will see that we start the “using component_name” formula to include (specify) the components we are going to use within our application. This is important because the compiler will know where to find a function when you call it. This is the key with commercial components and libraries too. You purchase a component and then you can use all of its functions any time, anywhere.

Now that you know the basics, let’s see those three implementations in C#.

{mospagebreak title=Implementations}

The first implementation relies on the System.Web.Mail component that is part of the .NET 1.0 and 1.1 Framework. This is useful for those of you coding in older environments. Check out the attached block of code.

// works only in pre-.NET 2.0. Frameworks (1.0 or 1.1)

. . .

using System.Web.Mail;

. . .

SmtpMail.SmtpServer = "smtp.mail.com";

string from = "jondoe@bla.net";

string to = "justme@isp.com";

string subject = "voila";

string body = "sdfsdfsdf, yes, it’s all about sdfsdfsdf.";

SmtpMail.Send(from, to, subject, body);

As you can see at first we specify the component that we’ll use later on. Right after that we need to specify the SmtpServer. This is the address of the SMTP server. Then we also need those four strings of “from address,” “to address,” “subject,” and “body” of the e-mail message that is going to be sent. Once we get all of this prepared, we just call the Send function from the SmtpMail class— voila!

For extensive documentation regarding the capabilities of System.Web.Mail components I strongly and wholeheartedly suggest reading this website.

Now let’s see the second solution. Here we’re going to use the System.Net and System.Net.Mail components, all located within the currently latest frameworks.

// works only in post-.NET 2.0. Frameworks (2.0, 3.5)

. . .

using System.Net;

using System.Net.Mail;

. . .

MailMessage mail = new MailMessage();

mail.From = new MailAddress("jondoe@bla.net");

mail.To.Add("esther@mybusiness.net");

mail.Subject = "voila";

mail.Body = "sdfsdfsdf, yes, it’s all about sdfsdfsdf.";

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);

smtp.EnableSsl = true;

smtp.Credentials = new NetworkCredential("your_account@gmail.com", "your_password");

try

{

smtp.Send(mail);

}

catch (SmtpException ex)

{

MessageBox.Show(ex.Message, "Error: " + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);

}

Don’t be fooled by the length of the above block of code. It isn’t harder; it is just a little bit more extensive because I’ve opted for the GMail solution where both SSL encryption and the necessary Network Credentials are to be supplied in order to establish the connection with their SMTP server. Also, error handling isn’t neglected!

On the first lines we specify the components. We create a new MailMessage object called mail. Then we add content to its fields (from, to, subject, body). We head over to add the SMTP server details as well. The port we’re going to use here with GMail’s server is 587. We use EnableSsl to enable SSL (true is the boolean variable). And ultimately, we create a new NetworkCredential using your GMail account information.

Since you are going to do all of this just for yourself to learn and try things out, nobody is going to steal your password or anything. It is safe as long as you do not give out your code, however, you shouldn’t ever commercialize codes from tutorials because they are always way too simplistic and monetizing them is close to impossible. Anyway, play around and see how it works.

The try and catch block will “pick up” if there are any errors and you will get an error message box if that’s the case. You may get something like connection timed out (Wrong port? Slow connection?) or transfer failed (Wrong address? Wrong account information?) and so forth. If the mail goes through all right, you won’t get a message box. Have fun!

Once again, don’t forget to check out this site for extensive documentation on the capabilities, functions, and abilities of System.Net.Mail component. It is worthwhile to look into this because this isn’t obsolete like the earlier System.Web.Mail.

And here comes the final commercial example, using the Chilkat Mail component coming from Chilkat Software. You can download it from here. Keep in mind that you need to send any string through the UnlockComponent method in order to enter into the trial period. If you purchase a license, you will get a valid code that you should pass through the said method. Check out the attached source code.

Chilkat.MailMan mailman = new Chilkat.MailMan();

mailman.UnlockComponent("Unlock 30-day trial period");

mailman.SmtpHost = "smtp.server_goes_here.com";

Chilkat.Email mail = new Chilkat.Email();

mail.From = "Jeff Mike <jeff@mybusiness.com>";

mail.AddTo("Jon Doe", "jondoe@bla.net");

mail.Subject = "voila";

mail.Body = "sdfsdfsdf, yes, it’s all about sdfsdfsdf.";

bool success = mailman.SendMail(mail);

if (success)

{

Console.WriteLine("Done.");

}

else

{

Console.WriteLine(mailman.LastErrorText);

}

Let’s explain in short what the code does. We create a new MailMail object called mailman, unlock the component (trial period), add the SMTP server address, and right after that we create the mail Email object. We add the necessary fields such as From, Recipient (AddTo is used because it is added to a collection of recipients!), Subject, and Body. We also create a boolean variable called “success” just for error handling.

Surely, the above code assumes that you have downloaded and extracted the ChilkatDotNet.dll and added it as a reference into your project solution. If you have done all of this, then the code will compile and run without issues. For more practical examples using the Chilkat component just check out their official “example section.”

{mospagebreak title=Final Thoughts}

That’s right; we’ve just arrived at the end of this tutorial. By now you should know more than a few ways to accomplish the task of sending mails within C# applications. Whether you are working in an older environment on frameworks such as 1.0 or 1.1, or the latest ones such as 2.0 or 3.5, I have shown you how to do it.

You can also download the archived complete source code of the application that we created together in the earlier section. Since it is based on System.Net and System.Net.Mail, it works only with .NET 2.0 Frameworks or newer. I have used the Visual Studio 2005 IDE. Click on the button below to download, extract everything, and open the solution. I hope it will be useful.

Furthermore, I have introduced to you the concept of Chilkat .NET components (or libraries), a commercial package that you may want to check out in the future. Surely, for private and home use the 30-day trial is more than enough; you can play around with it and grasp its inner workings, but other than this it isn’t really worth it.

However, as a programmer, you are required to know and be familiar with as many components, extra libraries and components, as possible. Companies and software development firms often rely on commercial libraries and components because they can sometimes, not always, accomplish the same task more effectively without unnecessary effort. That’s why you also need to know what Chilkat is all about.

Finally, don’t hesitate to join our friendly community of technology experts, professionals, and enthusiasts in our field of expertise—Dev Hardware Forums. We cover areas like hardware, software, and consumer electronics. You are welcome to join, ask questions, or even debate some of the provocative topics in the world of IT&C. Also, don’t forget to check out the forums of our sister sites such as Dev Shed Forums.

[gp-comments width="770" linklove="off" ]