<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martijn's C# Programming Blog &#187; email</title>
	<atom:link href="http://www.dijksterhuis.org/tag/email/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using C# and .NET to send an e-mail through SMTP</title>
		<link>http://www.dijksterhuis.org/using-csharp-to-send-an-e-mail-through-smtp/</link>
		<comments>http://www.dijksterhuis.org/using-csharp-to-send-an-e-mail-through-smtp/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 07:02:26 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[email]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=744</guid>
		<description><![CDATA[
Sending an e-mail is pretty old news by now so it should come as no surprise that .NET contains a significant SMTP mail client. One old programming truth still holds: All programs will expand to eventually include sending (and receiving) e-mails. So how about adding e-mail to your program ? This post explores how we [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2009/03/email.jpg" alt="Sending an e-mail using .NET" title="Sending an e-mail using .NET" width="500" height="238" class="aligncenter size-full wp-image-749" /></p>
<p><em>Sending an e-mail is pretty old news by now so it should come as no surprise that .NET contains a significant SMTP mail client. One old programming truth still holds: All programs will expand to eventually include sending (and receiving) e-mails. So how about adding e-mail to your program ? This post explores how we can use the System.Mail.SmtpClient to send formatted e-mails. There are plenty of options available and we will explore most of them.</em></p>
<p><span id="more-744"></span></p>
<p><em></em>In another lifetime together with friends I wrote <a id="ltp8" title="a massive e-mail parser" href="http://brazerko.com/watergate/wgman/welcome.htm">a massive e-mail parser</a> for the then popular FidoNet, and the (for us) new RFC822 based Internet. Written in Pascal for DOS it chewed its way through megabytes of modem downloaded Usenet groups and e-mail for our local BBS, night after night. It was fun and I learned that when it comes to e-mail that there are no real standards, just broken implementations.</p>
<p>Some 15 years later things have become quite a bit easier. Sending an e-mail is as straightforward as calling a few basic library functions and .NET of course includes a solid implementation.</p>
<p><strong>Quickly sending an e-mail</strong></p>
<p>If you are in a hurry then the following constructor will create a simple mail message from just 4 string parameters:</p>
<pre class="brush: c#">
// public client.Send(string from,string to,string subject,string body)
using System.Net.Mail;
SmtpClient client = new SmtpClient();
client.Send(&quot;martijn@dijksterhuis.org&quot;,&quot;test@dijksterhuis.org&quot;,&quot;Testing!&quot;,&quot;If this break again,.. I won&#039;t know what to do&quot;);
</pre>
<p>In the above example the e-mail is send using the system default settings as discovered by the .NET framework. If you are curious which system acted as the Default SMTP server you can query SmtpClient.Host</p>
<blockquote><p>Console.WriteLine(&#8221;Default SMTP Server: {0}&#8221;,client.Host);</p></blockquote>
<p>Note that there is a good chance that the .NET libraries are unable to work out the SMTP host and will fail with an <em>System.InvalidOperationException</em> (The SMTP host was not specified) when you attempt to send the e-mail. </p>
<p><strong>Sending a proper e-mail</strong></p>
<p>An basic e-mail is build up out of a sender, one or more recipients, a message body and one or more attachments. And of course the e-mail is probably encoded in an outdated Russian font.</p>
<p>The e-mail sender and receiver are represented by the <em>MailAddress</em> class. So of course you need an e-mail address, optionally a name, and in case you really want to send a Russian formatted name, a proper encoding format.</p>
<pre class="brush: c#">
MailAddress toUser = new MailAddress(&quot;martijn@dijksterhuis.org&quot;);
MailAddress toUser2 = new MailAddress(&quot;martijn@dijksterhuis.org&quot;,&quot;Martijn Dijksterhuis&quot;);
MailAddress toUser3 = new MailAddress(&quot;martijn@dijksterhuis.org&quot;,&quot;Martijn Dijksterhuis&quot;, System.Text.Encoding.UTF8);
</pre>
<p>My name doesn&#8217;t include any funky characters so I specified the default UTF-8 encoding.</p>
<p><strong>Sending an e-mail with only a single sender and receiver</strong></p>
<p>If your e-mail only contains a single sender and a single receiver the <em>MailMessage(MailAddress From,MailAddress To)</em> constructor provides all you need. It creates a new e-mail message structure, assigning the sending and receiver in the constructor.</p>
<pre class="brush: c#">
MailAddress toUser = new MailAddress(&quot;myfriend@yahoo.com&quot;);
MailAddress fromUser = new MailAddress(&quot;martijn@dijksterhuis.org&quot;);
MailMessage msg  = new MailMessage(fromUser,toUser);
</pre>
<p><strong>Adding more receivers to the same e-mail</strong></p>
<p>A single recipient is probably not sufficient. Not to worry, you can add as many To&#8217;s, CC&#8217;s, BCC&#8217;s etc to the e-mail as you would like:</p>
<pre class="brush: c#">
msg.To.Add( new MailAddress(&quot;second_to@dijksterhuis.org&quot;) );
msg.CC.Add( new MailAddress(&quot;first_cc@dijksterhuis.org&quot;) );
msg.CC.Add( new MailAddress(&quot;second_cc@dijksterhuis.org&quot;) );
msg.Bcc.Add( new MailAddress(&quot;first_bcc@dijksterhuis.org&quot;) );
</pre>
<p><strong>Setting the E-mail subject and body content</strong></p>
<p>Setting the subject of the e-mail is not hard, just set it from <em>Msg.Subject</em>.  And if you would like to encode that in a format other the Unicode, say BIG-5 Chinese:</p>
<pre class="brush: c#">
msg.Subject = &quot;一分鐘換一年&quot;
msg.SubjectEncoding = Encoding.GetEncoding(&quot;big5&quot;);
</pre>
<p>(The above Chinese came from my junk box and to the best of my knowledge its harmless)</p>
<p>Setting the actual message body works in a very similar fashion:</p>
<pre class="brush: c#">
msg.Body = &quot;Dear Customer, &quot; + Environment.NewLine + Environment.NewLine;
msg.Body += &quot;Because of repeated violations of our terms and conditions we had no choice but to&quot;;
msg.Body += &quot;terminate your account with us.&quot; + Environment.NewLine + Environment.NewLine;
msg.Body += &quot;The Management&quot;;
msg.BodyEncoding = System.Text.Encoding.UTF8;
</pre>
<p><strong>Adding an attachment to the e-mail</strong></p>
<p>An e-mail can have more than one attachment, and each attachment is represented by the System.Net.Mail.Attachment class. You can add them to the attachment collection of the message by calling &#8220;Attachments.Add()&#8221;</p>
<pre class="brush: c#">
using System.Net.Mime;
Attachment firstAttachment = new Attachment(&quot;document.doc&quot;,MediaTypeNames.Application.Octet);
MailMessage msg  = new MailMessage(fromUser,toUser);
msg.Attachments.Add(firstAttachement);
</pre>
<p>The first parameter passed to the constructor is the path to the attachment to include. If no full path is given, the current working directory is tried. The file type is defined in <em>System.Net.Mime</em> &#8212; available options are:</p>
<table border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="33%">MediaTypeNames</td>
<td width="33%">Application</td>
<td width="33%">Octet</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">PDF</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">RTF</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Soap</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Zip</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%">Image</td>
<td width="33%">Gif</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">JPEG</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Tiff</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%">Text</td>
<td width="33%">HTML</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">Plain</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">RichText</td>
</tr>
<tr>
<td width="33%"></td>
<td width="33%"></td>
<td width="33%">XML</td>
</tr>
</tbody>
</table>
<p>If the type of file is not specified use <em>MediaTypesNames.Application.Octet</em> , which stands for &#8220;data is not interpreted&#8221;.</p>
<p><strong>Adding custom e-mail headers to your e-mail</p>
<p></strong>The <em>Msg.Header</em> property allows you to query and add to the e-mail headers set  by the .NET framework. A brand new e-mail will only contain a single header: &#8220;Mime: 1.0&#8243;. Adding your own custom header to this is trivial as is shown in the following code example: <strong><br />
</strong></p>
<pre class="brush: c#">

MailMessage Msg = new MailMessage(new               MailAddress(&quot;martijn@dijksterhuis.org&quot;),new MailAddress(&quot;martijn@dijksterhuis.org&quot;));

// Add a custom header to the e-mail
Msg.Headers.Add(&quot;X-Header&quot;,&quot;2.0&quot;);

// Display all the message headers.
string[] Keys = Msg.Headers.AllKeys;
foreach (string s in Keys)

Console.WriteLine(&quot;{0}: {1}&quot;, s,Msg.Headers[s]);
</pre>
<p><strong>Sending your e-mail with SmtpClient</strong></p>
<p>The hard work of delivering the e-mail is done through the <em>SmtpClient</em> class and the most basic delivery only takes two lines:</p>
<blockquote><p> SmtpClient client = new SmtpClient();<br />
 client.Send(Msg);
</p></blockquote>
<p>It might be wise to catch exceptions at this point because sending an SMTP e-mail can throw a number:</p>
<p><OL><br />
<LI>SmtpFailedRecipientsException: The message could not be delivered to one or more of the recipients in To, CC, or Bcc.</LI><br />
<LI>SmtpException : Connection failed, authentication failed or a time-out</LI><br />
<LI>ArgumentNullException / ArgumentOutOfRangeException / InvalidOperationException : Something wrong with the input fields of the e-mail</LI><br />
</OL></p>
<p>If you do not specify any parameters the default <em>SmtpClient</em> constructor will lookup the SMTP server to use through the .NET environment. </p>
<p>You can specify a specific server and optional port through the second constructor:</p>
<blockquote><p>SmtpClient client = new SmtpClient(&#8221;mail.dijksterhuis.org&#8221;,3000);</p></blockquote>
<p>The above <em>SmtpClient.Send</em> call is a blocking call &#8212; your application halts while the e-mail is being send. Naturally there is also an asynchronous call: <em>SmtpClient.SendAsync</em>.</p>
<p>Using <em>SmtpClient.SendAsync</em> is a little more work. How to do this is shown in the following example: </p>
<pre class="brush: c#">
using System;
using System.Net.Mail;
using System.Threading;
using System.ComponentModel;

namespace SnmpMailer
{
    class MainClass
    {
        static Semaphore mailSendSemaphore;

        private static void MailSendCallback(object sender, AsyncCompletedEventArgs arg)
        {
            // Get our unique token for this asynchronous operation.
            String token = (string) arg.UserState;

            // Did the user abort the sent ?
            if (arg.Cancelled)
                Console.WriteLine(&quot;[{0}] Send canceled.&quot;, token);
            // Did an error occur during the send?
            if (arg.Error != null)
                 Console.WriteLine(&quot;[{0}] {1}&quot;, token, arg.Error.ToString());
            else
                Console.WriteLine(&quot;Message sent succesfully!&quot;);

            // Release the main thread
            mailSendSemaphore.Release();
        }

        public static void Main(string[] args)
        {
            mailSendSemaphore = new Semaphore(0,1);

            /* Create the mail message with to &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; from */
            MailMessage Msg = new MailMessage(new MailAddress(&quot;noreply@dijksterhuis.org&quot;),
                                              new MailAddress(&quot;martijn@dijksterhuis.org&quot;));

            Msg.Body = &quot;Dear Customer, &quot; + Environment.NewLine + Environment.NewLine;
            Msg.Body += &quot;Because of repeated violations of our terms and conditions we had no choice but to&quot;;
            Msg.Body += &quot;terminate your account with us.&quot; + Environment.NewLine + Environment.NewLine;
            Msg.Body += &quot;The Management&quot;;
            Msg.BodyEncoding = System.Text.Encoding.UTF8;

            /* Set the subject */
            Msg.Subject = &quot;Termination of service notice&quot;;

            /* Add our own header */
            Msg.Headers.Add(&quot;X-Deliverator&quot;,&quot;Terminator&quot;);

            /* Deliver the message in an asynchronous fashion */
            SmtpClient Deliverator = new SmtpClient(&quot;mymailserver.com&quot;);

            /* Print the default client */
            Console.WriteLine(&quot;Default SMTP Server: {0}&quot;,Deliverator.Host);

            /* Specify the call back function */
            Deliverator.SendCompleted += new SendCompletedEventHandler(MailSendCallback);

            /* For an asyncronous call we can pass a token to help us determine the message being send */
            Deliverator.SendAsync(Msg,&quot;Msg ID 1212&quot;);

            /* Because we have little else to do, we set a semaphore and wait */
            mailSendSemaphore.WaitOne();

            Console.WriteLine(&quot;Mail delivery finished&quot;);
        }
    }
}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/biscotte/">Mzelle Biscotte</a></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/using-csharp-to-send-an-e-mail-through-smtp/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
