Sending Mail and Configuring Your Server for an ASP.NET 2.0 Email System

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.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 8
June 11, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

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.

Sending HTML Format Email

Similarly, according to the earlier explanations, it will take steps 1-6 and step 8, or seven steps altogether, to send HTML formatted e-mails. Here for brevity, we mainly list the different steps:

 

protected void NewBtn_Click(object sender,EventArgs e)

{

  ///……omit steps 1-5 (same as the above section);

  mailMsg.IsBodyHtml = HtmlCB.Checked;

  nContain += mailMsg.Body.Length;

  if(mailMsg.IsBodyHtml == true)

  {nContain += 100; }

  try

  { ///send email(s)

    IMail mail = new Mail();

    mail.SendMail(mailMsg);

    ///save them

    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)

  { ///……omitted}

  Response.Redirect("~/MailDesktop.aspx");

}

 

Sending Email with Attachments

As is introduced above, it will take all nine steps to send e-mail with attachments, which is the most complicated mode of sending e-mail. We mainly list the distinct part of the source code below:

 

protected void NewBtn_Click(object sender,EventArgs e)

{

  ///omit steps 1-6

  ///add the mail attachment(s)

  HttpFileCollection fileList = HttpContext.Current.Request.Files;

  for(int i = 0; i < fileList.Count; i++)

  { ///add each attachment

    HttpPostedFile file = fileList[i];

    if(file.FileName.Length <= 0 || file.ContentLength <= 0)

    { break;}

    Attachment attachment = new Attachment(file.FileName);

    mailMsg.Attachments.Add(attachment);

    nContain += file.ContentLength;

  }

  if(mailMsg.IsBodyHtml == true) {nContain += 100;}

  try

  { ///send email(s)

    IMail mail = new Mail();

    mail.SendMail(mailMsg);

    ///save them

    int nMailID = mail.SaveAsMail(mailMsg.Subject,mailMsg.Body,from,

      To.Text.Trim(),CC.Text.Trim(),mailMsg.IsBodyHtml,

      nContain,mailMsg.Attachments.Count > 0 ? true : false);

    if(nMailID > 0)

  { ///save the attachment(s) of the sent out email(s)

    for(int i = 0; i < fileList.Count; i++)

    { ///add each attachment

      HttpPostedFile file = fileList[i];

      if(file.FileName.Length <= 0 || file.ContentLength <= 0)

      { break;}

      ///save the attachment(s) into hard disk

      file.SaveAs(MapPath("MailAttachments/" + Path.GetFileName(file.FileName)));

    ///save the attachment(s) of the sent out email(s)

      mail.SaveAsMailAttachment(

        Path.GetFileName(file.FileName),

        "MailAttachments/" + Path.GetFileName(file.FileName),

        file.ContentType,

        file.ContentLength,

        nMailID);

      }

    }

  }

  catch(Exception ex)

  { ///……omitted}

  Response.Redirect("~/MailDesktop.aspx");

}

 

So far, we've discussed sending e-mails, with all the connected steps. Next, we will examine how to configure your e-mail server to ensure that e-mail will be sent out correctly and safely.

Configuring Your Email Server

Please note that here I'm going to show you a simple online e-mail sample system, so I'll only provide you with a few items to configure. Figure 2 shows the design time snapshot of the profile interface.

Figure 2-the design time snapshot for configuring the system

After the SystemProfile.aspx page has been initialized, the system displays the current configured information, such as information for the server IP, the mail server port, and so forth. This is done in the Page_Load function with the help of a helper function, BindWebMailProfile:

 

protected void Page_Load(object sender,EventArgs e)

{

  if(!Page.IsPostBack)

  { ///show the system configuration info

    BindWebMailProfile();

  }

}

private void BindWebMailProfile()

{ ///obtain the system configuration info

  IMail mail = new Mail();

  SqlDataReader dr = mail.GetWebMailProfile();

  if(dr.Read())

  {

    UserName.Text = dr["UserName"].ToString();

    AliasName.Text = dr["AliasName"].ToString();

    Email.Text = dr["Email"].ToString();

    IP.Text = dr["MailServerIP"].ToString();

    Port.Text = dr["MailServerPort"].ToString();

  }

  dr.Close();

}

 

Here, in the BindWebMailProfile function, we first create a new instance of the  Mail class, then call the GetWebMailProfile method of that class to obtain the configuration information from the SQL Server database. We then assign it to the corresponding fields on the page. Clicking the SetBtn button (i.e. OK) will trigger the SetBtn_Click event in which the newly-populated data are persisted back into the database. To do this, we've called the WebMailProfile method of the Mail class.

 

protected void SetBtn_Click(object sender,EventArgs e)

{

  try

  { ///define a new Mail object

    IMail mail = new Mail();

    ///execute the database operation

  mail.WebMailProfile(UserName.Text.Trim(),AliasName.Text.Trim(),
Email.Text.Trim(),

      IP.Text.Trim(),Int32.Parse(Port.Text.Trim()));

    Response.Write("<script>alert('" + "The system has been configured
successfully, please safekeep your data!" + "');</script>");

  }

  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",""));

  }

}

 

Please check back tomorrow for the continuation of this article.

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials