Sending Mail and Configuring Your Server for an ASP.NET 2.0 Email System
(Page 1 of 4 )
In the previous article, you learned many of the principles you need to know when building your own online e-mail system. In this second part of a four-part series, we will look at the various e-mail formats -- text, HTML, and with attachments -- and the code required to make the system able to send and receive those kinds of messages. You will also learn how to configure your e-mail server. It is strongly recommended that you read the first part of the series before reading this one.
A
downloadable .rar file is available for this article.
Sending Text Format Email
According to the analysis in the previous article, to send text-formatted e-mail it only takes steps 1-5 and step 8, or six steps in total. Feel free to check the first part of this series to refresh your memory. In any case, the corresponding code is as follows:
protected void NewBtn_Click(object sender,EventArgs e)
{
int nContain = 0;
///add the address of the sender
string from = ((WebMailProfile)HttpContext.Current.Application["WebMailProfile"]).Email;
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress(from);
nContain += mailMsg.From.Address.Length;
///add the address of the receiver
string split = ";";
string[] toList = To.Text.Trim().Split(split.ToCharArray());
for(int i = 0; i < toList.Length; i++)
{mailMsg.To.Add(toList[i].Trim()); }
nContain += To.Text.Length;
///add address for CC
string[] ccList = CC.Text.Trim().Split(split.ToCharArray());
for(int i = 0; i < ccList.Length; i++)
{
if(ccList[i].Trim().Length > 0) {
mailMsg.CC.Add(ccList[i].Trim());
}
}
nContain += CC.Text.Length;
///add topic
mailMsg.Subject = Title.Text.Trim();
mailMsg.SubjectEncoding = Encoding.UTF8;
nContain += mailMsg.Subject.Length;
///add mail body
mailMsg.Body = Body.Text;
mailMsg.BodyEncoding = Encoding.UTF8;
nContain += mailMsg.Body.Length;
if(mailMsg.IsBodyHtml == true)
{nContain += 100;}
try
{ ///send email
IMail mail = new Mail();
mail.SendMail(mailMsg);
///save the email that has just been sent out
int nMailID = mail.SaveAsMail(mailMsg.Subject,mailMsg.Body,from,
To.Text.Trim(),CC.Text.Trim(),mailMsg.IsBodyHtml,
nContain,mailMsg.Attachments.Count > 0 ? true : false);
catch(Exception ex)
{ ///jump to the page dealing with exception handling
Response.Redirect("ErrorPage.aspx?ErrorMsg=" + ex.Message.Replace("<br>","").Replace("n","")
+ "&ErrorUrl=" + Request.Url.ToString().Replace("<br>","").Replace("n",""));
}
Response.Redirect("~/MailDesktop.aspx");
}
Since enough annotations have been added and the earlier article covered a lot of ground, we won't dwell much on this code.
Next: Sending HTML Format Email >>
More ASP.NET Articles
More By Xianzhong Zhu