OogloO Web Design and Development - Pakistan

Friday, February 4, 2011

Joomla Web Design and Development

A professionally designed website is what gives your business a new life - and thats what oogloo does. We build top quality website for small to medium and emerging businesses; please review the portfolio of expertly designed, developed and maintained websites by The Best Joomla Web Design experts - OOGLOO solutions providers.

OOGLOO web design have a strong portfolio of CMS based websites design and development. We specialize in Joomla, with strong expertise in development and customization of Joomla templates and extensions. We are experts when it comes to making code-level customizations and development that includes php, mysql, jquery and other programming.

We also work to develop and customize widgets and themes for wordpress, drupal, magento, oscommerce and other open source CMS.

We can build a top quality cms based website for you; you can reach out to us for any of your web design needs that might include the following.

Tuesday, January 20, 2009

The Best Website Taglines Around the Internet

A tagline can make or break a website (well, maybe not, but it is cool to be dramatic). Below you will find a collection of the best taglines around the Internet. Some of them are funny, some are clever; but all of them deliver the message! Hopefully it will serve as inspiration.

The Straight Dope: Fighting Ignorance since 1973 (It’s taking longer than we thought).

Wednesday, August 27, 2008

In this and a series of articles that would follow, we would learn about threads and how to write multi-threaded programs in C#.

In this article we would learn what threads are and why they are needed. In part2 we would learn about threading with respect to the .NET framework. At the end of this article series you would have learnt how to create and manage threads, set thread priorities, determine thread states, thread pooling and thread synchronization.

Introduction

When the computers were first invented, they were capable of executing one program at a time. Thus once one program was completely executed, they then picked the second one to execute and so on. With time, the concept of timesharing was developed whereby each program was given a specific amount of processor time and when its time got over the second program standing in queue was called upon (this is called Multitasking, and we would learn more about it soon). Each running program (called the process) had its own memory space, its own stack, heap and its own set of variables. One process could spawn another process, but once that occurred the two behaved independent of each other. Then the next big thing happened. The programs wanted to do more than one thing at the same time (this is called Multithreading, and we would learn what it is soon). A browser, for example, might want to download one file in one window, while it is trying to upload another and print some other file. This ability of a program to do multiple things simultaneously is implemented through threads (detailed description on threads follows soon).

Multitasking vs. Multithreading

As explained above, Multitasking is the ability of an operating system to execute more than one program simultaneously. Though we say so but in reality no two programs on a single processor machine can be executed at the same time. The CPU switches from one program to the next so quickly that appears as if all of the programs are executing at the same time. Multithreading is the ability of an operating system to execute the different parts of the program, called threads, simultaneously. The program has to be designed well so that the different threads do not interfere with each other. This concept helps to create scalable applications because you can add threads as and when needed. Individual programs are all isolated from each other in terms of their memory and data, but individual threads are not as they all share the same memory and data variables. Hence, implementing multitasking is relatively easier in an operating system than implementing multithreading.

Hey, wait!!! all that's fine but I still do not understand fully what threads are!!!

What is a thread???

A thread can be defined as a semi-process with a definite starting point, an execution sequence and a terminating point. It maintains its own stack where it keeps the exception handlers, the scheduling priority and other details that the system might need to re-activate that thread.

Well, it seems like a complete process to me then why do we call it a semi-process!!!

That is because a full-blown process has its own memory area and data, but the thread shares memory and data with the other threads.

A process/program, therefore, consists of many such threads each running at the same time within the program and performing a unique task.

Threads are also called lightweight processes that appear to run in parallel with the main program. They are called lightweight because they run within the context of the full-blown program taking advantage of the resources allocated for the program.

On a single processor system, threads can be run either in a preemptive mode or in a cooperative mode.

In the preemptive mode, the operating system distributes the processor time between the threads and decides which thread should run next once the currently active thread has completed its time-share on the processor. Hence the system interrupts the threads at regular intervals to give chance to the next one waiting in the queue. So no thread can monopolize the CPU at any given point of time. The amount of time given to each thread to run depends on the processor and the operating system. The processor time given to each thread is so small that it gives the impression that a number of threads are running simultaneously. But, in reality, the system runs one thread for a couple of milliseconds, then switches to the other and so on. It keeps a count of all the threads and cycles through them giving each of them a small amount of the CPU time. The switching between threads is so fast that it appears as if all the threads are running simultaneously.

But, what does switching mean?? It means that the processor stores the state of the outgoing thread (it does so by noting the current processor register values and the last instruction-set the thread was about to perform), restores the state of the incoming thread (again by restoring its processor register values and picking the last instruction-set where it had left itself) and then runs it. But this style has its own flaws. One thread can interrupt another at any given time. Imagine what would happen if one thread was writing to a file and the other interrupted it and started writing to the same file. Windows 95/NT, UNIX use this style of managing their programs/threads.

In cooperative mode, each thread can control the CPU for as long as it needs it. In this implementation, one thread can starve all the others for processor time if it so chooses. However, if a thread is not using the processor it can allow another thread to use it temporarily. Running threads can only give up control either if a thread calls a yield function or if the thread does something that would cause it to block, such as perform I/O. Windows 3.x uses this kind of implementation.

On some systems, you can have both the cooperative and preemptive threads running simultaneously (Threads running with high priorities often behave cooperatively while threads running at normal priorities behave preemptively). Since you are not sure whether the system would let threads run in a cooperative or a preemptive model, it is always safer to assume that preemption is not available. You should be designing your program in such a way that processor-intensive threads should yield control at specific intervals. When the currently running thread wants to yield it means that the thread is willing to give up CPU control. The system then looks for threads that are ready to run and which are of the same or higher priority as the current thread. If it finds any then it pauses the execution of the current thread and activates the next thread, waiting in the queue. But, if it cannot find any thread of the same or higher priority then control returns to the thread that yielded. Still if a thread wants to give up control and let a thread of lower priority take over, then the thread goes into a sleep mode for a certain amount of time letting the lower priority thread run.

On a multi-processor system, the operating system can allocate individual threads to the separate processors, which thus fastens the execution of the program. The efficiency of the threads also increases significantly because the distribution of the threads on several processors is faster than sharing time-slices on a single processor. It is particularly useful to have a multi-processor system for 3D modeling and image-processing.

Are threads actually needed!!!

We all have fired a print command to print something. Imagine what would happen if the computer stopped responding while the printing is going on. Oh No!! Our work will come to a stop till the nasty print work is going on. But as we all know, nothing like this happens. We are able to do the normal work with the computer (like editing/saving a file) or drawing a graphic and listening to music etc without getting bothered with the print job. Now, this is possible because separate threads are executing all these tasks. You would have all noticed that the database or a web server interacts with a number of users simultaneously. How are they able to do that?? It is possible because they maintain a separate thread for each user and hence can maintain the state of all the users. If the program is run as one sequence then it is possible that failure in some part of the program will disrupt the functioning of the entire program. But, if the different tasks of the program are in separate threads then even if some part of the program fails, the other threads can execute independent of it and will not halt the entire program.

Wow!! This sounds good. So, if we start writing threaded applications, we would never come across those nasty crashes in our program.

Hold on!! We are not yet over.

No doubt, writing multithreaded applications gives you an edge over non-threaded applications but threading can become a very costly concept, if not used judiciously. A few apparent drawbacks are listed below. If one program has many threads, then threads in the other programs will naturally get less of the processor time. Besides, a large amount of processor time is consumed in controlling the threads. The system also needs sufficient memory to store the context information of each thread. Hence, large number of threads is a blow to memory, bugging the entire system and ultimately slowing the system down. Besides, a program has to be designed really well to support a large number of threads otherwise it would be more of a curse than a boon. While killing each of the threads you need to be aware of the repercussions that it might involve and handle them appropriately.

Designing threaded programs-few tips

There are numerous ways that you can design a good multi-threaded application. Here we would get a general glimpse but as we proceed (in the later parts of this article) you would understand things better. Threads can be of different priorities (we would see in the later parts of this article series how to decide their priority levels). Say, we need to draw a graphic or do a big mathematical computation and at the same time want to get user input. We should first keep all the individual tasks (like drawing an image, or doing computation or asking for user-input) in separate threads. We should then allocate a higher priority to the thread, which is expecting user-input so that its responsiveness is high, and the thread, which is drawing the graphic or doing the calculation, at a lower priority so that the entire CPU time is not bogged down by these tasks.

Again, say based on the user-input the program has to do some processing. If the processing is long then it may take some time to complete and the user is un-necessarily made to wait till it is over. In such cases, we should keep separate threads, one to read user input and the other to handle any lengthy operations based on the input. This will make the program more responsive. It will also give the user the flexibility to cancel the operation at any point of the running of the thread. Hence, applications that use user-input should always have one thread to handle input, which will keep the user interface active at all times, and let the processor-intensive tasks execute on separate threads

In the case of drawing graphics, the application should always be listening to messages (like a repaint command) from the system. If the application gets busy doing some other work then the screen might remain blank for a long time, which of course is not very appealing visually. So, in such cases it is advisable to have one thread always dedicated to handling messages (like repaint) from the underlying system.

Always remember that a thread, which manages time-critical tasks, should be given a high priority and the others a low priority. Like the thread listening for client requests should always remain responsive and hence allotted high priority. A user-interface thread that manages interactions with the users should delegate all requests immediately to the worker threads rather than trying to work on those requests. This way, it will remain responsive to the users at all times.

Conclusion:

This is just the first of the series of articles that we are going to study on multi-threading. In this part we have got familiarity with what threads are and why they are needed. In the next part we would learn how threading is implemented in C#.

Tuesday, August 26, 2008

The following is a FAQ about System.Web.Mail and some of the questions that are asked about it.

1.1 What is System.Net.Mail?

System.Net.Mail is the namespace used to send email if you are using the 2.0 (or higher) .NET Framework.

Unlike System.Web.Mail, which was introduced in the 1.0 Framework, it is not built upon the CDO/CDOSYS libraries. Instead it is written from the ground up without any interop. Thus, it is not dependant upon other COM libraries. System.Net.Mail introduces brand new classes for creating and sending email.

Although some functionality has been removed, the new System.Net.Mail namespace is much more versatile than the older CDO dependant System.Web.Mail.

1.2 What is the .NET Framework ?

The answer to this question is waaay beyond the scope of this faq. Basically the .NET Framework is a engine that programmers use to create applications. Programmers code against the .NET Framework to create applications. The System.Web.Mail Namespace is part of the .NET framework. You can read more about the .NET Framework on MSDN at http://msdn.microsoft.com/netframework/ .

1.3 What do I need to send email in .NET?

First, and foremost, you need the .NET Framework installed. Then you need a reference to the System.dll (automatically included in ASP.NET applications). Then you need to use the System.Net.Mail namespace to create and send email messages.
Once you have programmatically set up your application, you will need a relay server to send email through. A relay server is a mail server, or a SMTP server/service, that can handle sending email. System.Net.Mail simply sends the mail to a relay server, and the relay server is responsible for delivering it to the final destination.

1.4 What is a relay server?

A relay is a service that allows you to send email. It is usually a full fledged mail server, or can be a specialized SMTP Service. Some examples of a mail server include Microsoft Exchange, IMail by IPSwitch, or Mail Enable by Mail Enable. An example of a SMTP service is the SMTP Service installed that can be installed with IIS. SNM sends email to a relay server, and the relay server is responsible for delivering the email to the final destination. When sending email to a relay server, you must have protocol permissions to use that server. Because of SPAM problems, relay servers are normally locked down, either by IPAddress or by some type of username/password authentication. Relaying errors are the most common problems when programmatically sending emails. If you ever see an exception that reads something like "550 Permission Denied", this is usually a relay error, and you need to talk to your mail server administrator about proper permissions.

1.5 What is the IIS SMTP Service?

The IIS SMTP service is a SMTP service used for sending email. It handles all of the MX Record (Mail server location) lookups, SMTP connections to remote mail servers, retries, and failures. More information about configuring the SMTP Service can be found here: Manage Your Company's E-mail with the Windows 2000 SMTP Service http://www.microsoft.com/mind/1299/smtp2000/smtp2000.asp

1.6 Can System.Net.Mail read email?

No. System.Net.Mail can only send email. To read email you either need a Mime parsing component such as aspNetMime or a POP3 component such as aspNetPOP3.

2 Exploring System.Net.Mail Classes

This FAQ section will explore the main classes of the System.Net.Mail name space. This is not a complete listing of all the classes, but rather the ones that are most commonly used. They include:

The MailMessage class can be considered the foundation class of the System.Net.Mail namespace. It deals with creating and managing the email message. All other classes will somehow interact with this class. The MailMessage class exposes such properties as the

The MailAddress class is used for creating email addresses. This class is used for setting the MailMessage.From, MailMessage.To, MailMessage.CC and MailMessage.BCC properties. Of these properties the .From class is actually a MailAddress, while the To, CC and BCC properties are actually collections of MailAddresses. The two most common properties of the MailAddress class are the DisplayName and the Address properties. They are described below.

//set the addresses
//to specify a friendly 'from' name, we use a different ctor
mail.From = new MailAddress("me@mycompany.com", "Steve James");

//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
//since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple times
mail.To.Add("you@yourcompany.com");
mail.To.Add("you2@yourcompany.com");
mail.CC.Add("cc1@yourcompany.com");
mail.CC.Add("cc2@yourcompany.com");
mail.Bcc.Add("blindcc1@yourcompany.com");
mail.Bcc.Add("blindcc2@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

'set the addresses
'to specify a friendly 'from' name, we use a different ctor
mail.From = New MailAddress("me@mycompany.com", "Steve James")

'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
'since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple times
mail.To.Add("you@yourcompany.com")
mail.To.Add("you2@yourcompany.com")
mail.CC.Add("cc1@yourcompany.com")
mail.CC.Add("cc2@yourcompany.com")
mail.Bcc.Add("blindcc1@yourcompany.com")
mail.Bcc.Add("blindcc2@yourcompany.com")

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'MultipleRecipients

The Attachment class is used for creating and managing individual attachments of the MailMessage object. Attachments can be created from streams or file paths. The stream or file path must be set in the ctor of the Attachment.

The SmtpClient class is responsible for sending or transporting the email. The SmtpClient can transport the email content over the network, or it can actually write them to the filesystem in the MS IIS Smtp Service Pickup Directory format, which resembles a RFC821 formatted message. Emails can be sent either synchronously or asynchronously. The SmtpClient also supports sending email via SSL for security purposes. The following list of properties are the most common used on the SmtpClient class.

The AlternateView class is used for providing alternate bodies and creating Multi-Part mime emails. If you want to create an email that will be rendered properly in both Html capable and Plain Text only mail clients, then you will create alternate views of the message. There are a few main properties and methods you will use with the AlternateView class. They are:

//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("this is bold text, and viewable by those mail clients that support html", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

'first we create the Plain Text part
Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")
'then we create the Html part
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("this is bold text, and viewable by those mail clients that support html", Nothing, "text/html")
mail.AlternateViews.Add(plainView)
mail.AlternateViews.Add(htmlView)

The LinkedResource class is the last, and least used main class. It is mainly used for creating embedded images. To create an embedded image you will need to first create a Html formatted AlternateView. Within that alternate view you create an tag, that points to the ContentId (CID) of the LinkedResource. You then create a LinkedResource object and add it to the AlternateView's LinkedResources collection.

//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");

//then we create the Html part
//to embed images, we need to use the prefix 'cid' in the img src value
//the cid value will map to the Content-Id of a Linked resource.
//thus will map to a LinkedResource with a ContentId of 'companylogo'
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.", null, "text/html");

'first we create the Plain Text part
Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")

'then we create the Html part
'to embed images, we need to use the prefix 'cid' in the img src value
'the cid value will map to the Content-Id of a Linked resource.
'thus will map to a LinkedResource with a ContentId of 'companylogo'
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.", Nothing, "text/html")

This System.Web.Mail QuickStart is a series of samples and supporting commentary designed to quickly acquaint developers with the syntax of sending email in .NET. The QuickStart samples are designed to be short, easy-to-understand illustrations of System.Net.Mail.

Important: When testing these samples, always be sure to:1. Have a reference set to the System.dll.
2. If you are using C#, be sure the "using System.Net.Mail;" statement is found at the top of your code. Or, if you are using VB.NET, be sure the "Imports System.Net.Mail" statement if found at the top of your code.
3. Set the correct FROM and TO addresses.
4. Set the SmtpMail.SmtpServer to a valid server that allows relaying for your FROM email address or the IP address you are sending email from.

3.1 Working with the Body

This section of the FAQ will deal with creating different types of email bodies. From Plain Text formatted emails, to Html formatted emails, to creating Multi-Part Mime emails.

'set the content
mail.Subject = "This is an email"
mail.Body = "this is a sample body with html in it. This is boldThis is blue"
mail.IsBodyHtml = True

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)

3.1.3 How do I create a Multi-Part mime message?

This example will demonstrate creating a Multi-Part mime message. Multi-Part messages are messages that contain alternate body parts. Alternate body parts are used for displaying different content to different mail clients. Because it is impossible to sniff or determine an end users' mail client application, it is left up to the email developer to cover all formats. You simply create different, alternate body parts. Then, it is up to the mail client to display the richest body part it can render.

The following example creates the most common Multi-Part mime email, a Plain Text and a Html Text email (2 alternate body parts).

//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("this is bold text, and viewable by those mail clients that support html", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

'first we create the Plain Text part
Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")
'then we create the Html part
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("this is bold text, and viewable by those mail clients that support html", Nothing, "text/html")
mail.AlternateViews.Add(plainView)
mail.AlternateViews.Add(htmlView)

//set the addresses
//to specify a friendly 'from' name, we use a different ctor
mail.From = new MailAddress("me@mycompany.com", "Steve James");

//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
mail.To.Add( new MailAddress( "you@yourcompany.com", "Beth Jones") );
mail.CC.Add(new MailAddress("donna@yourcompany.com", "Donna Summers"));
mail.Bcc.Add(new MailAddress("bob@yourcompany.com", "Bob Smith"));

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

'set the addresses
'to specify a friendly 'from' name, we use a different ctor
mail.From = New MailAddress("me@mycompany.com", "Steve James")

'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
mail.To.Add(New MailAddress("you@yourcompany.com", "Beth Jones"))
mail.CC.Add(New MailAddress("donna@yourcompany.com", "Donna Summers"))
mail.Bcc.Add(New MailAddress("bob@yourcompany.com", "Bob Smith"))

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'FriendlyToName

3.2.3 How do I specify multiple recipients?

Because the To, CC, and Bcc properties are MailAddress collections, to add additional recipients, all we need to do is call .Add(...) on the respective properties.

Below is an example that demonstrates adding multiple To, CC, and Bcc addresses.

//set the addresses
//to specify a friendly 'from' name, we use a different ctor
mail.From = new MailAddress("me@mycompany.com", "Steve James");

//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
//since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple times
mail.To.Add("you@yourcompany.com");
mail.To.Add("you2@yourcompany.com");
mail.CC.Add("cc1@yourcompany.com");
mail.CC.Add("cc2@yourcompany.com");
mail.Bcc.Add("blindcc1@yourcompany.com");
mail.Bcc.Add("blindcc2@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

'set the addresses
'to specify a friendly 'from' name, we use a different ctor
mail.From = New MailAddress("me@mycompany.com", "Steve James")

'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
'since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple times
mail.To.Add("you@yourcompany.com")
mail.To.Add("you2@yourcompany.com")
mail.CC.Add("cc1@yourcompany.com")
mail.CC.Add("cc2@yourcompany.com")
mail.Bcc.Add("blindcc1@yourcompany.com")
mail.Bcc.Add("blindcc2@yourcompany.com")

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'MultipleRecipients

3.2.4 How do I create a friendly non-ascii display name?

When we want to use non-ascii display names we have to specify an Encoding that matches the characterset of the name (string). This is something that needs to be known at the time of development.

Below is an example of creating a friendly display name that uses ISO-8859-1 characters.

//set the addresses
//to specify a friendly non ascii name, we use a different ctor.
//A ctor that accepts an encoding that matches the text of the name
mail.From = new MailAddress("me@mycompany.com", "Steve Øbirk", Encoding.GetEncoding( "iso-8859-1"));
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

'set the addresses
'to specify a friendly non ascii name, we use a different ctor.
'A ctor that accepts an encoding that matches the text of the name
mail.From = New MailAddress("me@mycompany.com", "Steve Øbirk", Encoding.GetEncoding("iso-8859-1"))
mail.To.Add("you@yourcompany.com")

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'FriendlyNonAsciiName

3.3 Working with Headers

This section of the faq will demonstrate working with headers of the MailMessage. From changing the messages' priority, to adding custom headers. We will explore different header names and values.

3.3.1 How do I change the email priority?

Although the priority of a message is controlled by headers, in the System.Net.Mail namespace, the Priority of a message is actually exposed as a property of the MailMessage object.

A priority can have the following values

Property

Description

High

The email has high priority.

Low

The email has low priority.

Normal

The email has normal priority.

The following example demonstrates setting the MailMessage object to a High priority.

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'specify the priority of the mail message
mail.Priority = MailPriority.High

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'SetPriority

3.3.2 How do I add the Reply-To header to the MailMessage?

Just the Priority property, the Reply-To header is set via a property called ReplyTo on the MailMessage object. Since the ReplyTo property is of type MailAddress, it can be a simple email address, or it can include a friendly display name.

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'specify the priority of the mail message
mail.ReplyTo = New MailAddress("SomeOtherAddress@mycompany.com")

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'SetTheReplyToHeader

3.3.3 How do I request a read receipt?

To request a read receipt, we need to specify a Disposition-Notification-To header. This header is recognized my most major mail clients to send a read receipt when the email is first read. It's important to note that just because you request a read receipt, doesn't' mean you will get one.

Read receipt requests may not be always honored because

1) A mail client may not recognize the special Disposition-Notification-To header.
2) A mail client may not implement that functionality.
3) The end user may have that functionality turned off.
4) The end user may optionally not choose to send one for your particular email.

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

//To request a read receipt, we need add a custom header named 'Disposition-Notification-To'
//in this example, read receipts will go back to 'someaddress@mydomain.com'
//it's important to note that read receipts will only be sent by those mail clients that
//a) support them
//and
//b)have them enabled.
mail.Headers.Add("Disposition-Notification-To", "");

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'To request a read receipt, we need add a custom header named 'Disposition-Notification-To'
'in this example, read receipts will go back to 'someaddress@mydomain.com'
'it's important to note that read receipts will only be sent by those mail clients that
'a) support them
'and
'b)have them enabled.
mail.Headers.Add("Disposition-Notification-To", "")

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'ReadReceipts

3.3.4 How do I add custom headers to the MailMessage?

Custom headers are useful for adding information to a MailMessage that may not be supported on standard properties. By adding custom headers, we can tag email messages with information that may not be visible to the end user, yet still might be important to us. This is especially useful in tracking bounced emails. By using custom headers, we can find our custom header in a bounced email, and perhaps tie it back to a record in the database.

Below is an example of adding two "X-" headers to a MailMessage. There isn't anything special about adding the prefix "X-" to a header. In the email world, the "X-" prefix has just come to mean "extra".

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'CustomHeaders

3.4 Working with Attachments

This FAQ section will demonstrate creating attachments from the filesystem and from a stream.

3.4.1 How do I send an email with attachments?

To send an email with attachments, the ASP.NET process (or the ASP.NET impersonated account) will need permission to read the file, and attach it to the MailMessage class. If the file is found in the website, we don't need use the explicit file path, we could also call Server.MapPath(...).

Below is a simple example of attaching text files to an outgoing email.

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'AttachmentFromFile

3.4.2 How do I create an attachment from a stream?

Something that is new in System.Net.Mail, is the capability to create attachments from streams. With this capability we can create an attachment from text, binary data, or from basically anything in memory. We simply need to make sure it is written to a stream.

The following example creates an attachment from some simple text, but it could have just as easily have come from Sql Server.

'set the content
mail.Subject = "This is an email"
mail.Body = "this content is in the body"

'Get some binary data
Dim data As Byte() = GetData()

'save the data to a memory stream
Dim ms As New MemoryStream(data)

'create the attachment from a stream. Be sure to name the data with a file and
'media type that is respective of the data
mail.Attachments.Add(New Attachment(ms, "example.txt", "text/plain"))

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'AttachmentFromStream

Function GetData() As Byte()
'this method just returns some binary data.
'it could come from anywhere, such as Sql Server
Dim s As String = "this is some text"
Dim data As Byte() = Encoding.ASCII.GetBytes(s)
Return data
End Function 'GetData

3.5 Accessing Config File Mail Settings Programmatically

Some people may not know that .NET 2.0 provides APIs for accessing everything in a configuration file. The most common question I see relates to accessing the mail settings in the system.net node programmatically.

This System.Net.Mail advanced samples is a series of code samples and supporting commentary designed to perform advanced email operations. Some of the topics discussed here cannot be achieved using System.Net.Mail, but are listed for completeness, and because I have seen these questions asked on various newsgroups and lists.

4.1 How do I read SMTP configuration data?

Using special settings in your app's configuration file, System.Net.Mail can configure itself.

Using the configuation file, you can set the following default properties:

MailMessage.From
SmtpClient.Host
SmtpClient.Port

The settings will also allow you specify a Username and Password to be used for authentication. It is important to note that if DefaultCredentials are specified to true, the userName and password attributes are igorned.

Here is an example of the node:

<configuration>
<system.net>
<mailSettings>
<smtpfrom="me@mycompany.com">
--
The node supports the following properties, but we won't use all of them
-->
<networkhost="127.0.0.1"/>
smtp>
mailSettings>
system.net>
configuration>

4.10 How do I create a log file of the SMTP session?

The System.Net namespace allows you to log the contents of the SMTP session to a file. This is done through a combination of trace switches in your app's configuration file.

The following example of trace switches will cause the SMTP session to be logged to a file named "System.Net.trace.log".

In this example, an exception was actually thrown. The exception basically said I don't have permission to relay through the mail server to send email.

4.11 How do I encrypt messages using s/mime or pgp?

You can't. System.Net.Mail does not support encrypted messages.

4.2 How do I authenticate to send an email?

To authenticate with System.Net.Mail is much more intuitive than it was with System.Web.Mail. No longer do you have to set a fields property. Instead, you simply create a NetworkCredential's object, and set the username and password.

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'send the message
Dim smtp As New SmtpClient("127.0.0.1")

'to change the port (default is 25), we set the port property
smtp.Port = 587
smtp.Send(mail)
End Sub 'ChangePort

4.4 How do I embed images in an email?

Embedding images is something that is new with System.Net.Mail. To embed an image you will need to

Create a LinkedResource object. The LinkedResource will actually contain the binary data of the Image. This binary data is encoded as part of the email, and sent along as part of the MailMessage.

Give the LinkedResource a unique name, also known as a Content-Id.

Create a HTML AlternateView.

Inside that HTML text, you need to use the standard tag.

For the "src" value, you need to point it at the Content-Id of the LinkedResource image. This is done by using the syntax The "src=cid:" part is required for the email client to recognize the tag as an embedded image, while the "whatever" part is the actual Content-Id of the LinkedResource image. This will instruct the mail client to find an embedded image named "whatever" and display the contents *without* making a http:// request.

That's all there is to create a linked image. Below is a short but complete example that demonstrates creating an embedded image.

//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");

//then we create the Html part
//to embed images, we need to use the prefix 'cid' in the img src value
//the cid value will map to the Content-Id of a Linked resource.
//thus will map to a LinkedResource with a ContentId of 'companylogo'
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.", null, "text/html");

'first we create the Plain Text part
Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")

'then we create the Html part
'to embed images, we need to use the prefix 'cid' in the img src value
'the cid value will map to the Content-Id of a Linked resource.
'thus will map to a LinkedResource with a ContentId of 'companylogo'
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.", Nothing, "text/html")

Sending an email over Ssl is really simply with System.Net.Mail. In fact, all you need to do is set the .EnableSsl property on the SmtpClient property to true.

Below you will find an example of of SMTP over SSL.

Note: Due to what I believe is a bug in System.Net.Mail you *cannot* use SSL and Credentials (username/password) at the same time. I was never able to get that to work. I always got an exception from the remote mail server. I believe it has to do with the steps System.Net.Mail takes to initiate the SSL session and SMTP authentication.

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
//the userstate can be any object. The object can be accessed in the callback method
//in this example, we will just use the MailMessage object.
object userState = mail;

//wire up the event for when the Async send is completed
smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'send the message
Dim smtp As New SmtpClient("127.0.0.1") 'specify the mail server address
'the userstate can be any object. The object can be accessed in the callback method
'in this example, we will just use the MailMessage object.
Dim userState As Object = mail

'wire up the event for when the Async send is completed
AddHandler smtp.SendCompleted, AddressOf SmtpClient_OnCompleted

If e.Cancelled Then
Console.WriteLine("Send canceled for mail with subject [{0}].", subject)
End If
If Not (e.Error Is Nothing) Then
Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString())
Else
Console.WriteLine("Message [{0}] sent.", subject)
End If
End Sub 'SmtpClient_OnCompleted

4.7 How do I write to the Pickup directory?

Writing email to the IIS Server's SMTP service pickup directory is another new feature of System.Net.Mail. The SMTP pickup directory is a special directory used by Microsoft's SMTP service to send email. Any email files found in that directory are processed and delivered over SMTP. If the delivery process fails, the files are stored in a queue directory for delivery at another time. If a fatal error occurs (such as a DNS resolution error), the files are moved to the Badmail directory.

By writing to the pickup directory, this speeds up the process because the entire chatting SMTP layer used for relaying is by passed. Below is an example of how to write directly to the Pickup directory.

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

//if we are using the IIS SMTP Service, we can write the message
//directly to the PickupDirectory, and bypass the Network layer
SmtpClient smtp = new SmtpClient();
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Send(mail);
}

[ VB.NET ]

Public Sub PickupDirectory()
'create the mail message
Dim mail As New MailMessage()

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'if we are using the IIS SMTP Service, we can write the message
'directly to the PickupDirectory, and bypass the Network layer
Dim smtp As New SmtpClient()
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis
smtp.Send(mail)
End Sub 'PickupDirectory

4.8 How do I send a web page?

System.Net.Mail does not natively support sending a web page. However, using the WebRequest class, you can screen scrape web pages, and pass the resulting Html string to the MailMessage object. The following example demonstrates this technique.

Note: Be sure to import the System.Net and System.IO namespaces for this code snippet.

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'EmailWebPage

Public Function ScreenScrapeHtml(ByVal url As String) As String
Dim objRequest As WebRequest = System.Net.HttpWebRequest.Create(url)
Dim sr As New StreamReader(objRequest.GetResponse().GetResponseStream())
Dim result As String = sr.ReadToEnd()
sr.Close()
Return result
End Function 'ScreenScrapeHtml

4.9 How do I send non US-ASCII emails?

In the beginning, when email was first being used, it was all us-ascii content. To handle different languages and character sets, different encodings must be used. The following example demonstrates sending a non us-ascii email, using the ISO-8859-1 character set as an example. The hardest part of sending non us-ascii email, is to determine the correct character set. For reference, an easy to use character set chart can be found at aspNetEmail's website, here: http://www.aspnetemail.com/charsets.aspx .

//to send non-ascii content, we need to set the encoding that matches the
//string characterset.
//In this example we use the ISO-8859-1 characterset
mail.Body = "this text has some ISO-8859-1 characters: âÒÕÇ";
mail.BodyEncoding = Encoding.GetEncoding("iso-8859-1");

'to send non-ascii content, we need to set the encoding that matches the
'string characterset.
'In this example we use the ISO-8859-1 characterset
mail.Body = "this text has some ISO-8859-1 characters: âÒÕÇ"
mail.BodyEncoding = Encoding.GetEncoding("iso-8859-1")

'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'NonAsciiMail

5 Troubleshooting System.Net.Mail

System.Net.Mail seems like a pretty stable class of email objects. There are a few known issues. I'm sure more will crop up over time. At the time I put this FAQ together, System.Net.Mail has been out of beta for less than 30 days. Check the forums for more ideas and help.

If you do get any exceptions, be sure to always check the inner exception for more additional information. Usually the inner exceptions will provide the additional information to solve your problem. Here's a code example for checking inner exceptions in a console application. If you want to use this code in an ASP.NET page, be sure to change Console.WriteLine(...) to Response.Write(...).

Bcc stands for Blind Carbon Copy. You typically BCC someone on an email when you don't want any of the other recipients to know someone else is being copied on the email. Unfortunately there is a bug in System.Net.Mail when you BCC someone. If you look at the raw headers of the sent mail message you will see X-Receiver header for everyone that was sent the message. This includes the To, CC, and BCC addresses. Thus anyone who was BCC'd on the message is recorded in headers.

5.2 Cannot enable SSL with a username and password.

I don't really know if this is a problem or not, but I have not been able to enable SSL and also use a username/password for authentication. I believe this has to do with the order in which System.Net.Mail sends the commands to the SMTP server. For whatever reason I received an "Authentication failed" exception from the remote SMTP server. As soon as I turned SSL off, everything worked. If I didn't set a username/password, the SSL session worked just fine. It was the combination of SSL and a username/password that wouldn't let me email.

6 Additional Help

The following list of links are places to find additional information on System.Net.Mail

System.Net.Mail Forums
You can use the forums found on this site for discussing different System.Net.Mail issues. The forums are found here:
http://www.SystemNetMail.com/forums.aspx