System.Net.Mail Advanced Programming,May be you are not aware.Worth Reading

I hope several guys had used , using  and going to use System.Net.Mail for thier email sending module regardless whether it is a web or window application.

But I am sure may not be aware of some advanced email  sending techniques,Okay here it is last night when I was talking with one of my open source project UK team member.He was asking about how to send embedded images along with email using System.Net.Mail and I told him that these things are mostly forgotten to learn by most of the .NET developers.

So I decided write an article which are very advanced email programming like faq

How do I read SMTP configuration data?

Using special settings in your app’s configuration file, System.Net.Mail can configure itself.
Using the configuation file, you can set the following default properties:

MailMessage.From
SmtpClient.Host
SmtpClient.Port
 

The settings will also allow you specify a Username and Password to be used for authentication. It is important to note that if DefaultCredentials are specified to true, the userName and password attributes are igorned.

Here is an example of the  <mailSettings> node:

<configuration>
  <system.net>
    <mailSettings>
      <smtp from=”me@mycompany.com“>
        <!–
            The <network> node supports the following properties, but we won’t use all of them
            <network host=”127.0.0.1″ port=”25″ userName=”myUserName” password=”secret” defaultCredentials=”true” />
        –>
        <network host=”127.0.0.1″ />
       </smtp>
    </mailSettings>
   </system.net>
</configuration>

How do I embed images in an email?
Embedding images is something that is new with System.Net.Mail. To embed an image you will need to

 

  1. Create a LinkedResource object. The LinkedResource will actually contain the binary data of the Image. This binary data is encoded as part of the email, and sent along as part of the MailMessage.

  2. Give the LinkedResource a unique name, also known as a Content-Id.

  3. Create a HTML AlternateView.

  4. Inside that HTML text, you need to use the standard <img> tag.

  5. For the “src” value, you need to point it at the Content-Id of the LinkedResource image. This is done by using the syntax <img src=”cid:whatever”> The “src=cid:” part is required for the email client to recognize the <img> tag as an embedded image, while the “whatever” part is the actual Content-Id of the LinkedResource image.  This will instruct the mail client to find an embedded image named “whatever” and display the contents *without* making a http:// request.

That’s all there is to create a linked image. Below is a short but complete example that demonstrates creating an embedded image.

static void EmbedImages()
{
//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress(“me@mycompany.com”);
mail.To.Add(“you@yourcompany.com”);

//set the content
mail.Subject = “This is an email”;

//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString(“This is my plain text content, viewable by those clients that don’t support html”, null, “text/plain”);

//then we create the Html part
//to embed images, we need to use the prefix ‘cid’ in the img src value
//the cid value will map to the Content-Id of a Linked resource.
//thus <img src=’cid:companylogo’> will map to a LinkedResource with a ContentId of ‘companylogo’
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(“Here is an embedded image.<img src=cid:companylogo>”, null, “text/html”);

//create the LinkedResource (embedded image)
LinkedResource logo = new LinkedResource( “c:\\temp\\logo.gif” );
logo.ContentId = “companylogo”;
//add the LinkedResource to the appropriate view
htmlView.LinkedResources.Add(logo);

//add the views
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

//send the message
SmtpClient smtp = new SmtpClient(“127.0.0.1”); //specify the mail server address
smtp.Send(mail);
}

How do I send email asynchronously?

System.Net.Mail has also added asynchronous support for sending email. To send asynchronously, you need need to

  1. Wire up a SendCompleted event
  2. Create the SendCompleted event
  3. Call SmtpClient.SendAsync

These steps are demonstrated in the code below.

       static void SendAsync()
        {
            //create the mail message
            MailMessage mail = new MailMessage();

            //set the addresses
            mail.From = new MailAddress(“me@mycompany.com”);
            mail.To.Add(“you@yourcompany.com”);

            //set the content
            mail.Subject = “This is an email”;
            mail.Body = “this is the body content of the email.”;

            //send the message
            SmtpClient smtp = new SmtpClient(“127.0.0.1”); //specify the mail server address
            //the userstate can be any object. The object can be accessed in the callback method
            //in this example, we will just use the MailMessage object.
            object userState = mail;

            //wire up the event for when the Async send is completed
            smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);

            smtp.SendAsync( mail, userState );
        }
        public static void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //Get the Original MailMessage object
            MailMessage mail= (MailMessage)e.UserState;

           //write out the subject
            string subject = mail.Subject;

            if (e.Cancelled)
            {
                Console.WriteLine(“Send canceled for mail with subject [{0}].”, subject);
            }
            if (e.Error != null)
            {
                Console.WriteLine(“Error {1} occurred when sending mail [{0}] “, subject, e.Error.ToString());
            }
            else
            {
                Console.WriteLine(“Message [{0}] sent.”, subject );
            }
        }

How do I send a web page?
System.Net.Mail does not natively support sending a web page. However, using the WebRequest class, you can screen scrape web pages, and pass the resulting Html string to the MailMessage object. The following example demonstrates this technique.

 

Note: Be sure to import the System.Net and System.IO namespaces for this code snippet.

public static void EmailWebPage()
        {
            //create the mail message
            MailMessage mail = new MailMessage();

            //set the addresses
            mail.From = new MailAddress(“me@mycompany.com”);
            mail.To.Add(“you@yourcompany.com”);

            //set the content
            mail.Subject = “This is an email”;

            //screen scrape the html
            string html = ScreenScrapeHtml(“http://localhost/example.htm&#8221;);
            mail.Body = html;
            mail.IsBodyHtml = true;

            //send the message
            SmtpClient smtp = new SmtpClient(“127.0.0.1”);
            smtp.Send(mail);

        }
        public static string ScreenScrapeHtml(string url)
        {
            WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
            StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream());
            string result = sr.ReadToEnd();
            sr.Close();
            return result;
        }

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s