Pages

Advertisement

Saturday, July 14, 2007

Another example to send Email via Asp.Net

E-mail is one of the most common and reliable methods of communication for both personal and business purposes. It also plays an important role in each and every Web site. This role will be in the type of automated e-mails from the server after posting information from a form. You may have noticed these types of e-mails while registering on a site. As soon as you post the form, the server will send an e-mail asking you to confirm either your registration or with the information you entered. If you have to confirm the registration, the server will send you a long URL that you have to click to proceed further with the registration process. A classic example of this functionality is ASP.NET forums. As soon as you register, you will be e-mailed a random password. You will also get e-mails after your post has been accepted by a moderator or if somebody replies to your post. If you are wondering that this is a server magic—it is not. The whole process is made possible with the help of server-side programming languages such as ASP and ASP.NET.

Classic ASP provided a component named CDONTS that a developer should use intelligently to provide e-mail functionality on his or her applications. But this component lacked major functionalities. You can easily send an e-mail, but the process is very difficult for sending e-mails with attachments, HTML versions, and so forth. Almost all server-side languages provide some sort of solution for achieving these tasks. But, ASP.NET simplified the work of developers with the introduction of a special .NET namespace called System.Web.Mail. Moreover, it is very tedious to upload a file to a server with ASP. You have to depend upon third-party components. ASP.NET ships with a cute built-in uploading capability with which your users can easily upload their files. They can also send the file as an attachment along with their e-mails. In this article, you will learn how to send different types of e-mails with ASP.NET.

To send e-mails, you should require access to a server with .NET Framework and SMTP enabled on it. SMTP stands for Simple Mail Transfer Protocol and e-mails are sent using this protocol. If you don't have a paid server space, you can register for a free ASP.NET hosting account at a site such as http://europe.webmatrixhosting.net/.

The .NET Framework supplies a SMTP class that enables you to send a simple e-mail message. If you have to send an e-mail with added functionalities, you have to make use of the MailMessage class. With the help of this class, you can insert attachments, set priorities, and much more, very easily. You can also send HTML e-mail using this class.

Sending a Simple E-Mail Message

To send an e-mail with a simple text message, you have to use the Send() method of SMTP class. The syntax of the Send() method is shown in Listing 1.1 and an example is shown in Listing 1.2:

Listing 1.1

[Visual C# .NET]

SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY");

[Visual Basic .NET]

SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY")

Listing 1.2

[Visual C# .NET]

SmtpMail.Send("info@mydomain.com","hello@hello.com","Thank You",
"We look forward to working with you again in the
future");

[Visual Basic .NET]

SmtpMail.Send("info@mydomain.com","hello@hello.com","Thank You", _
"We look forward to working with you again in the _
future")

You can place the above code either on the form's Load() event or in a button control.

Sending E-Mail Messages Using WebForm Controls

The main problem with the code given in Listing 1.2 is that you have to change the parameter values each time for sending different mail messages. To solve this problem, you should build a User Interface using the required WebForm controls, as shown in Figure 1.


Figure 1: The User Interface

As you can see, the above User Interface is made up of two text boxes, one multiline text box, and a button. I have also applied ASP.NET validation controls to the above GUI to avoid errors. For more information regarding the usage of validation controls, refer to my previous articles Performing Validations with ASP.NET — Part 1 and Performing Validations with ASP.NET — Part 2.

Instead of supplying all parameters in the Send() method, you can define properties and their corresponding values separately by creating an instance of the MailMessage class. With the help of this class, you can easily add attachments, set priorities, BCC, CC values, and much more. Table 1, given at the end of this article, shows a list of properties of the MailMessage class. Add the code given in Listing 1.3 by double-clicking the button captioned Submit:

Listing 1.3

[Visual C# .NET]

MailMessage objEmail          = new MailMessage();
objEmail.To = txtTo.Text;
objEmail.From = txtFrom.Text;
objEmail.Cc = txtCc.Text;
objEmail.Subject = "Test Email";
objEmail.Body = txtName.Text + ", " +
txtComments.Text;
objEmail.Priority = MailPriority.High;
//SmtpMail.SmtpServer = "localhost";
try{
SmtpMail.Send(objEmail);
Response.Write("Your Email has been sent sucessfully -
Thank You");
}
catch (Exception exc){
Response.Write("Send failure: " + exc.ToString());
}

[Visual Basic .NET]

  Dim objEmail as New MailMessage()
objEmail.To = txtTo.Text
objEmail.From = txtFrom.Text
objEmail.Cc = txtCc.Text
objEmail.Subject = "Test Email"
objEmail.Body = txtName.Text & ", " &txtComments.Text
objEmail.Priority = MailPriority.High
'SmtpMail.SmtpServer = "localhost"
try
SmtpMail.Send(EMail)
Response.Write(Your E-mail has been sent sucessfully - _
Thank You)

catch exc as Exception
Response.Write("Send failure: " + exc.ToString())
End Try

Note: If you are using your local system (Server = localhost) instead of a real live server, you should properly enable relying on the Internet Information Server (IIS).

When you execute the above code, the server not only displays a confirmation message but also sends an e-mail to the address mentioned in the To and Cc text boxes with the information you entered in the respective fields. It is not necessary for you to enter a Cc address, but it is shown here as part of the explanation. Further, the e-mail will be sent with the highest priority.

Table 1: MailMessage class properties

Property
Description

Attachments
Used for sending e-mails with attachments

From
Sender's e-mail address

To
Recipient's e-mail address

Cc
Recipient's e-mail address (Carbon Copy)

Bcc
Recipient's e-mail address (Blind Carbon Copy)

Body
Text of the e-mail message

BodyFormat
Specifies the format of an e-mail message (Possible Values: Text, Html)

Priority
Specifies the priority of an e-mail message (Possible Values: High, Low, and Normal)

Subject
Denotes the subject of an e-mail message

Headers
Denotes a collection of acceptable headers (Example: Reply-To)

BodyEncoding
Specifies the method of encoding an e-mail message (Possible Values: Base64 and UUEncode)

Sending HTML E-Mail Messages

If you would like to send the above e-mail in HTML Format, simply add the code given below to the above listing:

[Visual C# .NET]

objEmail.BodyFormat = MailFormat.Html;

[Visual Basic .NET]

objEmail.BodyFormat = MailFormat.Html

You can download the complete source code by clicking here.

Fast and Simple Mobile Access to Pocket Outlook Data

For a new developer tool function to be useful, it must be easy to implement, provide a significant benefit to the task at hand, and perform well. As a Windows Mobile developer, I believe the addition of managed classes for accessing and interacting with the data contained within Pocket Outlook (contacts, tasks, and appointments) meets all these criteria.

 

Developers who build .NET Compact Framework applications for Pocket PCs and Smartphones must all-too-often provide access to Pocket Outlook data. Previously, this meant using P/Invoke to either call native DLLs' functionalities or access internal data stores directly, or acquiring third-party managed code libraries. The result was increased development time and/or increased cost. With the new managed classes, C# and VB .NET Compact Framework developers can quickly gain access to this often-vital information and modify it (if necessary) without additional products.

The ABCs of Pocket Outlook Access

To utilize the new managed classes for Pocket Outlook, you need the following:

The new managed classes are not available for Windows Mobile 2003 Second Edition or earlier devices. You can, however, use Visual Studio 2005 to develop either .NET Compact Framework 1.0 or 2.0 projects that take advantage of the new managed classes.

You need to perform only a few basic steps to access Pocket Outlook data from a Smart Device project in Visual Studio 2005:

  1. Add references to required assemblies.
  2. Create an instance variable for a Pocket Outlook session.
  3. Access the needed collection of information (appointments, tasks, contacts).
  4. Work with the collection.
  5. Dispose the Pocket Outlook session object.

By performing these steps, you can gain access to any information you need.

Adding References to Your Project

To gain access to the new managed classes for Pocket Outlook, you need to add references to two .NET Compact Framework assemblies to your project. You'll find Microsoft.WindowsMobile.dll and Microsoft.WindowsMobile.PocketOutlook.dll in the Add References dialog, as shown in Figure 1.

Figure 1: Necessary References for Pocket Outlook Access

From a coding perspective, you access classes only in the Microsoft.WindowsMobile.PocketOutlook namespace. The other assembly is required, however, because the PocketOutlook assembly has dependencies on the first assembly for interfaces.

The PocketOutlook namespace contains a vast array of classes. Figure 2 shows just some of the available classes you'll see in the Visual Studio Object Browser.

Figure 2: PocketOutlook Namespace Viewed in the Object Browser

Going forward, this article points out some of the more relevant classes to get you started.

Creating an OutlookSession Instance

For developers who have worked with the object model for Microsoft Outlook on the desktop, the Pocket Outlook object model should seem quite familiar. The object hierarchy and tasks associated with programming against this object model are very similar. One example of this is the initial programming step for accessing Pocket Outlook data: creating an instance of an Outlook session.

In the sample project, I created a single form containing a ListView control (named lvAppt) that I programmatically populate with Appointment information. Figure 3 shows this screen in design mode.

Figure 3: Appointments Screen in Design Mode

As you can see, I set up the ListView control into three columns for relevant appointment information. I use a ListViewItem object and its associated SubItems collection to populate this information.

To hold an instance of the PocketOutlook session, I created an instance variable in my form class named AppSession:

private OutlookSession AppSession;

For this demonstration, I added code to the form's constructor (immediately following the call to the InitializeComponent method that creates the instance of the PocketOutlook session):

public Form1()
{
InitializeComponent();

//Create an instance of the Pocket Outlook session
AppSession = new OutlookSession();

Accessing the Appointments Collection

The PocketOutlook object hierarchy provides simple access to collections of information. The collections are exposed through properties representing the folders containing associated items. They are accessed directly from the OutlookSession object. The most commonly used of these objects are the following:


Each of these categories also has associated collection objects in the forms of AppointmentCollection, TaskCollection, and ContactCollection. In my sample project, I need to access appointments. So, I created an instance variable to hold an Appointment collection (named AppAppts). To access the Appointments collection, I use the following code:

//Capture the AppointmentCollection into a variable
AppAppts = AppSession.Appointments.Items;

Once you have the collection, you can access individual items using the Appointment object. In my project, I used this object in conjunction with a foreach loop to walk through the collection:

//We now iterate through the entire collection with a foreach,
//using an appointment object...
foreach (Appointment appt in AppAppts)
{
//Create a ListViewItem object
lviAppt = new ListViewItem ();

//Add the appointment date to the ListViewItem, and the time
//and subject to ListViewItem SubItems
lviAppt.Text = appt.Start.ToShortDateString();

lviAppt.SubItems.Add(appt.Start.ToShortTimeString());
lviAppt.SubItems.Add(appt.Subject);

//Add the ListViewItem to the ListView
lvAppts.Items.Add(lviAppt);
}

Note: The Task object for tasks and the Contact object for contacts can be used for this same purpose. Each of these objects provides programmatic access to all of the properties that are stored locally in the Pocket Outlook data stores. Figure 4 shows some of the properties associated with a Task object in the Object Browser.



Figure 4: Task Object Properties Displayed in the Object Browser

 


Disposing the Pocket Outlook Session Object

When you have completed use of the Pocket Outlook data, you should dispose the session object to free up resources. To do this, simply call the Dispose method of the session instance:

//Don't forget to close the PocketOutlook session when done!
AppSession.Dispose();

Running the Completed Project

 


he completed code for this sample project looks like the following:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Microsoft.WindowsMobile;
using Microsoft.WindowsMobile.PocketOutlook;

namespace OutlookMobileAPI
{
public partial class Form1 : Form
{
private OutlookSession AppSession;
private AppointmentCollection AppAppts;
private ListViewItem lviAppt;

public Form1()
{
InitializeComponent();

//Create an instance of the Pocket Outlook session
AppSession = new OutlookSession();

//Capture the AppointmentCollection into a variable
AppAppts = AppSession.Appointments.Items;

//We now iterate through the entire collection with a
//foreach, using an appointment object...
foreach (Appointment appt in AppAppts)
{
//Create a ListViewItem object
lviAppt = new ListViewItem();

//Add the appointment date to the ListViewItem, and
//the time and subject to ListViewItem SubItems
lviAppt.Text = appt.Start.ToShortDateString();
lviAppt.SubItems.Add(
appt.Start.ToShortTimeString()
);
lviAppt.SubItems.Add(appt.Subject);

//Add the ListViewItem to the ListView
lvAppts.Items.Add(lviAppt);
}

//Don't forget to close the PocketOutlook session
//when done!
AppSession.Dispose();

}
}
}

Before running the application in the emulator, you will need to add some data for appointments. You can do this easily by first bringing up the emulator using the Tools -> Connect to Device. option from the Visual Studio menu. I added three appointments to the emulator, as shown in Figure 5.


Figure 5: Test Data for the Sample Project

When the project is compiled and run in the emulator, it displays the three appointments, as shown in Figure 6.


Figure 6: Sample Data Dsiplayed in the Sample Application

As you can see, very little code is required to expose Pocket Outlook data to your .NET Compact Framework application!

Using the ChooseContactDialog Class

Another useful class in the new managed APIs is the ChooseContactDialog class (also referred to as the Contact Picker). Simply put, use this class in your application to bring up a Contact selection dialog and return the selected contact to your application. This can be extremely useful when you want to quickly provide your user with a means of selecting contact information.

To use the Contact Picker, you will need to add a reference to the Microsoft.WindowsMobile.Forms.dll assembly to your project (this is where the ChooseContactDialog class resides.). To demonstrate this functionality, I created a simple Smart Device project consisting of one form. The form contains holders for information in the form of TextBox and Label objects, and it has one button (see Figure 7).


Figure 7: Contact Picker Demonstration Form

When the user chooses the Select. button in the application, the Contact Picker is displayed and the user can choose a contact. Once selected, the application populates information from the associated Contact object into the fields for display.

To accomplish this, I added the following code to the button's Click event handler to display the Contact Picker:

//Create the instance of the Contact Picker and disable the
//ability to create new contacts from it.
ChooseContactDialog appContactDialog = new ChooseContactDialog();
appContactDialog.HideNew = true;
appContactDialog.ShowDialog();

I then created logic (surrounded by a try...catch block in case the user backs out of the process) to capture the selected contact into an instance variable (named AppContact) and assign the form fields:

try
{
appContact = appContactDialog.SelectedContact;

textBox1.Text = appContact.FileAs;
lblMobile.Text = appContact.MobileTelephoneNumber.ToString();
lblPhone.Text = appContact.HomeTelephoneNumber;
}
catch
{
MessageBox.Show("No contact selected");
}

Before running this code in the emulator, I once again need to make sure that I have some contact records available. I used the Connect to Device. menu option in Visual Studio 2005 to populate two records.

When I run the application in the emulator and tap on the button, the Contact Picker appears (see Figure 8).


Figure 8: Contact Picker Displayed

Selecting a contact then returns control to my application, resulting in the contact data being displayed (see Figure 9).


Figure 9: Contact Information Displayed in the Application

Once again, the total amount of coding required for this functionality was very minimal. The following is the complete code for the form class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile;
using Microsoft.WindowsMobile.Forms;
using Microsoft.WindowsMobile.PocketOutlook;

namespace ContactPickerDemo
{
public partial class Form1 : Form
{
//Contact object instance
private Contact appContact;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//Create the instance of the Contact Picker and disable
//the ability to create new contacts from it.
ChooseContactDialog appContactDialog =
new ChooseContactDialog();
appContactDialog.HideNew = true;
appContactDialog.ShowDialog();

try
{
//Assign the selected contact to a Contact object
appContact = appContactDialog.SelectedContact;

//Populate the form fields
textBox1.Text = appContact.FileAs;
lblMobile.Text =
appContact.MobileTelephoneNumber.ToString();
lblPhone.Text = appContact.HomeTelephoneNumber;
}
catch
{
//If the user backed out, display a message.
MessageBox.Show("No contact selected");
}
}
}
}
 

Give Users an Invaluable Resource

For applications that require either extending the existing functionality of Pocket Outlook applications or integrating with Pocket Outlook data, the new managed classes exposed in Windows Mobile 5.0 and the .NET Compact Framework are an invaluable resource. With a minimal amount of time and effort, your Smart Device project can read and manipulate task, contact, and appointment information. If you have been hesitant to add this functionality to your application before, I strongly urge you to reconsider. For others, now might be a good time to evaluate the benefits of providing this type of functionality to your end users.

Sending Mail with ASP.NET 2.0

In ASP.NET 2.0, Microsoft deprecated the System.Web.Mail namespace and replaced it with System.Net.Mail. The new library introduces some new features, but it also includes some bugs in how mail is sent. Before discussing some of these in detail, let's go through some code sample (which assumes you've added a using System.Net.Mail at the top of the file):

MailMessage msg = new MailMessage();
msg.From = new MailAddress("address@domain.com", "Person's Name");
msg.To.Add(new MailAddress("destination@domain.com",
"Addressee's Name");
msg.To.Add(new MailAddress("destination2@domain.com",
"Addressee 2's Name");
msg.Subject = "Message Subject";
msg.Body = "Mail body content";
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
SmtpClient c = new SmtpClient("mailserver.domain.com");
c.Send(msg);

 


The code is similar with some minor changes to how you address the message. Instead of constructing an address, you can let the system do that for you. If you specify an e-mail address and a name, it will automatically display in the message as this:

"Person's Name" <destination@domain.com>

This is the "proper" form for an e-mail address. You can add multiple addresses to the To, CC, and BCC collections in the same way as shown above. This is programmatically easier to do than sending lots of messages—just add multiple addresses to the BCC property in order to send a mass mailing.

Now, About Those Bugs...

As previously mentioned, this new namespace has a couple of bugs. The first is when you send a message the headers are all added in lowercase letters. While the RFC for SMTP mail doesn't specify how the headers should be capitalized, many spam filters restrict messages where the headers are not properly capitalized.

The other bug deals with the Priority setting, which should mark a message as important within the mail client. Because of the way the header is formatted, my mail program (Eudora) doesn't recognize it as the priority flag and doesn't mark the message as important. While this seems trivial, it's a change from the System.Web.Mail version for no apparent reason. I'm continuing to research this and if I can't find a good fix, I may switch back to System.Web.Mail and deal with the warning messages that Visual Studio displays about System.Web.Mail being deprecated.

 

Hey it was really simple in asp.net as compared to any other languages ...