Send Personalized Emails using System.Net.Mail

In this blog post, We will learn how to send personalized emails to our clients. At first, Just create a txt file called "MailTemplate.txt" in your application root folder containing the below

Dear <user>,

This is a test for the process of sending personalized emails taking advantage of the power of System.Net.Mail introduced in ASP.NET 2.0

Best Regards,

<company>

What we will do in the next section is to merge the above template with the MailMessage Class. (user and company will be replaced through our code).

              // Create a dictionary generic collection and add the values of user and company
            Dictionary<string, string> d = new Dictionary<string,string>();
            d.Add("<user>",User.Identity.Name);
            d.Add("<company>","MyCompany");

        // Create instance of the MailDefinition Class
            MailDefinition md = new MailDefinition();
        // Set its Body file name to the template already created
            md.BodyFileName = "MailTemplate.txt";
        // use the CreateMailMessage function of the MailDefinition class to set the To, Collection
            MailMessage ms = md.CreateMailMessage("haissam50@hotmail.com", d, new LiteralControl());
        // Set the from Property
            ms.From = new MailAddress("haissam@haissam.com");
        // Set the subject
            ms.Subject = "Personalized Email";
        // Create an instance of the SmtpClient class
            SmtpClient sm = new SmtpClient();
        // Send the email
            sm.Send(ms);

Of course, you need to configure the Mail Settings in your web.config file.

Hope this helps

 

Comments

# re: Send Personalized Emails using System.Net.Mail

Thursday, February 14, 2008 10:01 AM by Bashar Kokash

Thanks, this is very helpfull.

but is it the same when dealing with html message?

# re: Send Personalized Emails using System.Net.Mail

Wednesday, February 20, 2008 6:01 PM by Tmac

This is great but can it be done in asp.net VB?

# re: Send Personalized Emails using System.Net.Mail

Wednesday, February 20, 2008 9:15 PM by tmac603

Yo where do you put this code? and can it be done with VB?  

# send personalized emails

Saturday, March 15, 2008 4:08 PM by send personalized emails

Pingback from  send personalized emails

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.