Creating Your Own Online E-mail System in ASP.NET 2.0

With network technologies developing rapidly, Internet traffic becomes more smooth and feasible. Today, therefore, more people use various online e-mail systems which greatly facilitate them nearly anywhere in the world. In this article, I will show you a rather complicated sample to explain the key techniques behind building such a system entirely with Microsoft ASP.NET 2.0 plus Microsoft SQL Server Express Edition.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 37
June 06, 2007
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable .rar file is available for this article.

Since the amount of ground to be covered won't all fit in one article, the material will be covered in four parts. This first part will introduce the topic and dissect the key techniques.

Requirements and Goals

The online e-mail system to be introduced in this series of articles is actually a common online mailbox, with which you can send various kinds of e-mail, such as e-mail in text format, HTML format, and with attachments. Using the system in this series, you will also be able to manipulate your mailboxes and e-mail, such as by looking up the mailboxes and the e-mail in them.

Concretely, the main functions enabled by this system can be enumerated as follows:

  • Sending common e-mails
  • Sending HTML-formatted e-mails
  • Sending e-mails with attachments
  • Configuring the mail server
  • Checking your mailboxes
  • Checking the e-mails in your mailboxes
  • Creating, renaming and deleting the folders
  • Reading your e-mails
  • Deleting your e-mails
  • Moving your e-mails

Does this sound like a very useful and fun project? The next section will show you how to design the underlining part -- the database tier.

Database Design

With the general goals in mind, we can now focus upon the database design.

 

Author's Note: Here you're assumed to be familiar with SQL Server 2005 Express Edition and the basic SQL grammar. In addition, to follow along with the example, you'd better download the source files accompanying this article, available in a link immediately after the introduction.

 

In this article, we'll design a database named WebMailDatabase.mdf, which contains four tables: Folders for holding mailbox folders, Mails for storing all the e-mails, Attachments for storing all the attachments of the related e-mails, and WebMailProfiles for holding information to configure your mail server. 

Now, for brevity, the table structures of the four tables are listed in table form respectively as follows:

Table 1-Structure for Folders Table

Field name

Type

Notes

FolderID

int(4)

Primary Key identifying the record

Name

varchar(50)

The name of the mailbox

Total

int(4)

The number of the e-mails contained in this mailbox

NoReader

int(4)

The number of the unread e-mails

Contain

int(4)

The size of the mailbox

CreateDate

datetime(8)

Tells when the mailbox was created

Flag

bit(1)

Marks whether it's a self-defined mailbox

Table 2-Structure for Mails Table

Field name

Type

Notes

MailID

int(4)

ID(Primary Key)

Title

varchar(255)

The title of the e-mail

Body

text(16)

The body of the e-mail

FromAddress

text(16)

The sender list of the e-mail

ToAddress

text(16)

The receiver list of the e-mail

CCAdress

text(16)

The CC list of the e-mail

HTMLFormat

bit(1)

Specifies whether it is an HTML-formatted e-mail 

SenderDate

datetime(8)

The send date list of the e-mail

Contain

int(4)

The size of the mailbox

AttachmentFlag

bit(1)

Specifies whether there are attachments in this e-mail

ReaderFlag

bit(1)

Specifies whether this e-mail has been read

FolderID

int(4)

ID of the related mailbox

Table 3-Structure for Attachments Table

Field name

Type

Notes

AttachmentID

int(4)

ID(Primary Key)

Name

varchar(50)

The name of the attachment

Url

varchar(255)

linking address of the attachment

Type

varchar(50)

Type of attachment

Contain

int(4)

size of the attachment

MailID

int(4)

The ID of its related e-mail

Table 4-Structure for WebMailProfiles Table

Field name

Type

Notes

WebMailID

int(4)

ID(Primary Key)

UserName

varchar(50)

The user name

AliasName

varchar(50)

The alias name of the user

Email

varchar(255)

The e-mail address of the user

MailServerIP

varchar(50)

The ID address of the mail server

MailServerPort

int(4)

The port of the mail server

Besides these four tables, we've also defined three stored procedures, namely Pr_DeleteMail, Pr_MoveMail and Pr_SaveAsMail used to delete the e-mails, move the e-mails and save the e-mails sent out, respectively. Here we don't list their relevant sql scripts, since there is still a long journey for us to make. For all detailed information, please refer to the downloadable source files accompanying this article.

Dissecting the Key Techniques: Interface Design

On the whole, there are two crucial parts in constructing the e-mail system: one is sending out the e-mails of different kinds, the other is profiling your mail server. To grasp the ideas in the two parts, you should acquaint yourself with the MAIL related API provided by the .NET 2.0 framework. Now let's look more closely at each part.

Sending E-mail

Here, we are merely interested in three kinds of mail (which in fact are the most commonly used), i.e. text format e-mails, HTML format e-mails, and those with attachments. Note that all these are done inside the Sender.aspx page.

1. Interface design

The following Figure 1 gives you the design time snapshot of the Sender.aspx page.

Figure 1-The design time snapshot of the Sender.aspx page

Since there is nothing peculiar here but the usual components for manipulating an e-mail, let's not chatter much about the controls but go on with the story.

Dissecting the Key Techniques: Sending Email

2. Sending emails

The whole process of sending email is rather complicated especially when the email contains attachments. Let's examine the detailed steps in terms of the three scenarios mentioned above, as follows:

1) Obtain the mail address of the sender, i.e. get the address the user has configured in the profile. The following gives the crucial code snippet associated with this:

 

string from =((WebMailProfile)HttpContext.Current.Application["WebMailProfile"]).Email;

MailMessage mailMsg = new MailMessage();

mailMsg.From = new MailAddress(from);

 

2) Add the addresses of the receivers. Since there may be more than one address receiving the e-mail, you need to get the address of every recipient from the string containing these addresses, and append them one by one to the To property of the MailMessage-mailMsg object:

 

string split = ";";

string[] toList = To.Text.Trim().Split(split.ToCharArray());

for(int i = 0; i < toList.Length; i++)

{

  mailMsg.To.Add(toList[i].Trim());

}

 

3) Add the CopyTo (i.e. CC) addresses. There may be more than one of this kind of address; your approach should be similar to the one taken above: 

 

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());

}

}

 

4) Add the topic of the mail and give the appropriate coding algorithm:

 

mailMsg.Subject = Title.Text.Trim();

mailMsg.SubjectEncoding = Encoding.UTF8;

 

5) Append the body of the e-mail and also specify the coding methods:

 

mailMsg.Body = Body.Text;

mailMsg.BodyEncoding = Encoding.UTF8;

 

6) Specify the format of the email as HTML by default:

 

mailMsg.IsBodyHtml = HtmlCB.Checked;

 

7) Add the attachments. Here the reason and the operation are just like those of steps 2 or 3 above, so we simply list the relevant code below:

 

HttpFileCollection fileList = HttpContext.Current.Request.Files;

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

{ ///adding 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;

}

 

8) Start sending your e-mail. First, call the SendMail method of the Mail class (the wrapper of the mailing related operation for simplification). Second, use the SaveAsMail method of the Mail class to persist the e-mails sent into the Sender mailbox:

 

IMail mail = new Mail();

mail.SendMail(mailMsg);

///save the mails to send

int nMailID = mail.SaveAsMail(mailMsg.Subject,mailMsg.Body,from, To.Text.Trim(),CC.Text.Trim(),mailMsg.IsBodyHtml,

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

 

9) If there are attachments for the e-mails, upload them to the hard disk of the server, and finally store information for these attachments in the database. This function is accomplished through the following:

 

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

{ ///add each attachment

  HttpPostedFile file = fileList[i];

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

  {break;}

  /// store these attachments into the hard disk

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

  /// save the attachments

  mail.SaveAsMailAttachment(

    Path.GetFileName(file.FileName),

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

    file.ContentType,

    file.ContentLength,

    nMailID);

}

 

Using SendMail

It's by using the SendMail method of the Mail class that you finally send out your e-mail. It first sets up the IP address and port for the mail server, then sets the mode of sending e-mails and whether to use user credentials, then finally it invokes the Send (MailMessage mailMsg) function to send the email.

 

public int SendMail(MailMessage mail)

{

  ///Define the client to sent the e-mail

  SmtpClient client = new SmtpClient();

  ///Set up the IP address of the mail server host

  client.Host = ((WebMailProfile)HttpContext.Current.Application["WebMailProfile"]).MailServerIP;

  ///set up the port of the mail server

  client.Port = ((WebMailProfile)HttpContext.Current.Application["WebMailProfile"]).MailServerPort;

  ///configure the properties for sending e-mails

  client.DeliveryMethod = SmtpDeliveryMethod.Network;

  //client.UseDefaultCredentials = false;

  client.UseDefaultCredentials = true;

  client.Credentials = new NetworkCredential("Xianzhong Zhu","abc123");

  //client.EnableSsl = true;

  ///send e-mail

  client.Send(mail);

  return (0);

}

 

 

Author's Note: When you debug this sample, you should carefully populate the system profile info. From above, you can see that my mail server requires my mailbox to provide the user name and password and use the user credentials, but there is no need to provide an SSL link. This may be different from your mail server's request. So here I hard-code the user name and password ( 'abc123' is the password of my sample mailbox-sdmyzxz2007test@163.com), and when you run this sample, please give the proper information according to your mail server's request.

 

Please check back next week 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 6 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials