Step 1. Create as aspx page and name it "SendMailWithTemplate.aspx".
<body>
Step 2. Add an html file NewAccountTemplate as shown below:
Step 3. This is a simple html file with placeholder which we will replace at runtime.
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSendEmail" Text="send mail using mail defination" runat="server" onclick="btnSendEmail_Click" />
<asp:Label ID="errorMsg" runat="server"></asp:Label>
</div>
</form>
</body>
Step 2. Add an html file NewAccountTemplate as shown below:
Step 3. This is a simple html file with placeholder which we will replace at runtime.
Step 4. Modify your web.config file to include the section
<system.net>
<mailSettings>
<smtp>
<network host="your host name here..." port="25" userName="username here...." password="password goes here...."/>
</smtp>
</mailSettings>
</system.net>
Step 5. Now in .cs file in the button click event we use MailDefination class(Hidden jem in Asp.Net) to use html template file.
protected void btnSendEmail_Click(object sender, EventArgs e)
{
MailMessage msg = CreateMessage();
try
{
SmtpClient sc = new SmtpClient();
sc.Send(msg);
}
catch (HttpException ex)
{
errorMsg.Text = ex.ToString();
}
}
protected MailMessage CreateMessage()
{
MailDefinition md = new MailDefinition();
//here you give the template file name.
md.BodyFileName = "~/EmailTemplates/NewAccountTemplate.htm";
//md.CC = sourceCC.Text;
md.From = "baunthiyal_pankaj@abc.com";
md.Subject = "Testing Mailer Functionality in Asp.Net";
//IsBodyHtml=> don't forget to set this property otherwise,
//your mail would not be an html mail and you will
//see the html tags there.
md.IsBodyHtml = true;
md.Priority = MailPriority.High;
ListDictionary replacements = new ListDictionary();
replacements.Add("<%UserName%>", "Vipin");
replacements.Add("<%VerifyUrl%>", "anything4it.blogspot.in");
replacements.Add("<%Sender%>", "Pankaj Baunthiyal");
System.Net.Mail.MailMessage fileMsg;
//CreateMailMessage: first argument is the comman separated recipient address.
fileMsg = md.CreateMailMessage("pankaj.baunthiyal@xyz.com", replacements, this);
// fileMsg.Body.Replace
return fileMsg;
}
No comments:
Post a Comment