Think Big! Our new site released!

Lastly, we have released our new site, Think Big!, that would be a complete replacement for the current site. We have been working on that since  along time. Be sure to visit it regularly:

Think Big! http://ThinkBig.it.tc

Poll: How do you access your twitter account?

Happy Programmer Day! Thank You Programmers!

Programmer DayToday on the 256s day of the year we are celebrating Programmers and thank them for all they do. The history of Programmer Day is longer than the 2 year life of this site, but unfortunately a lack of comments and poor documentation have obfuscated that history.

Now, you can visit ProgrammerDay.info that was created to promote and provide a home for the day.

Would Bill Gates wears Santa Claus and gives us free versions of Visual Studio Team System and SQL Server Enterprise? hmmmm…

Happy Programmy Day!

Thank You All Programmers!

Book: Network Programming for the Microsoft .NET Framework

Network Programming for the Microsoft .NET Framework

Network Programming for the Microsoft .NET Framework

Anthony Jones , Jim Ohlund , and Lance Olson

0-7356-1959-X

Download Here

We made every effort to bring these books to you. If you found a bad link please report it to us as soon as possible.

In addition, you can find lots of books here.

ILMerge 2.9.0727 is now available

Latestly, Mike Barnett the developer of ILMerge released the new version 2.9.0727 which fixes major problems that was exist in the previous version 2.9.0210.

ILMerge is a utility that can be used to merge multiple .NET assemblies into a single assembly. ILMerge takes a set of input assemblies and merges them into one target assembly.

Read more abour ILMerge and download the new version v2.0.0727 here.

ILMerge is a utility that can be used to merge multiple .NET assemblies into a single assembly. ILMerge takes a set of input assemblies and merges them into one target assembly.ILMerge is a utility that can be used to merge multiple .NET assemblies into a single assembly. ILMerge takes a set of input assemblies and merges them into one target assembly.

مع الدوت نت, everything about .NET in Arabic

مع الدوت نت is a new Arabic site by the folks of Just Like a Magic devoted for .NET.

مع الدوت نت discusses many .NET topics in Arabic. It discusses new topics besides translating Just Like a Magic ’s hot topics.

Don’t hesitate to visit مع الدوت نت…

http://WithDotNet.WordPress.com

WithDotNet

Poll: How do you see our site?

A dozen of SQL Server books available for download

Advanced Transact-SQL for SQL Server 2000

Advanced Transact-SQL for SQL Server 2000

1-8931-1582-8

Download Now

Inside Microsoft SQL Server 2005 T-SQL Querying

Inside Microsoft SQL Server 2005: T-SQL Querying

0-7356-2313-9

Download Now

Microsoft SQL Server 2005 Database Essentials Step by Step

Microsoft SQL Server 2005: Database Essentials Step by Step

0-7356-2207-8

Download Now

Microsoft SQL Server 2005 The Complete Reference

Microsoft SQL Server 2005 The Complete Reference

0-0722-6152-8

Download Now

Steganos Internet Anonym VPN
Microsoft SQL Server 2005 Administrator's Companion

Microsoft SQL Server 2005 Administrator’s Companion

0-7356-2198-5

Download Now

Microsoft SQL Server 2005 Implementation and Maintenance

Microsoft SQL Server 2005 Implementation and Maintenance

0-7356-2271-X

Download Now

Microsoft SQL Server 2005 Reporting Services for Dummies

Microsoft SQL Server 2005 Reporting Services for Dummies

0-7645-8913-X

Download Now

Microsoft SQL Server 2005 Reporting Services Step by Step

Microsoft SQL Server 2005 Reporting Services Step by Step

0-7356-2250-7

Download Now

We made every effort to bring these books to you. If you found a bad link, please report it to us as soon as possible.

You may find more books here.

Fonts.com

AVG Internet Security - Tough on threats.

A dozen of ADO.NET books available for download

Microsoft .NET Enterprise Design with VB.NET and SQL Server 2000

.NET Enterprise Design with Visual Basic .NET and SQL Server 2000

0-6723-2233-1

Download Here

ADO.NET Cookbook

ADO.NET Cookbook

0-5960-0439-7

Download Here

ADO.NET Professional Projects

ADO.NET Professional Projects

1-9318-4154-3

Download Here

Beginning VB 2005 Databases

Beginning Visual Basic 2005 Databases

1-5905-9810-5

Download Here

Database Access with Visual Basic .NET

Database Access with Visual Basic .NET

0-6723-2343-5

Download Here

Database Programming with VB.NET and ADO.NET

Database Programming with Visual Basic .NET and ADO.NET

0-6723-2247-1

Download Here

Revitalize Your PC With PC Tune-Up
Mastering C# Database Programming

Mastering C# Database Programming

0-7821-4183-8

Download Here

Mastering VB.NET Database Programming

Mastering Visual Basic .NET Database Programming

0-7821-2878-5

Download Here

Microsoft ADO.NET Step by Step

Microsoft ADO.NET Step by Step

0-7356-1236-6

Download Here

Programming SQL Server 2000 with VB.NET

Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .NET

0-7356-1535-7

Download Here

Teach Yourself ADO.NET in 21 Days

Teach Yourself ADO.NET in 21 Days

0-6723-2386-9

Download Here

Teach Yourself ADO.NET in 24 Hours

Teach Yourself ADO.NET in 24 Hours

0-6723-2383-4

Download Here

We made every effort to bring these books to you. If you found a bad link, please report it to us as soon as possible.

You may find more books here.

Acrobat.com

NO priceline hotel cancellation or change fees

Sending Mails in .NET Framework

Contents

Contents of this article:

  • Overview
  • Introduction
  • Type Overview
    • System.Net.Mail Types
    • System.Web.Mail Types
  • SMTP Servers
  • Implementation
  • Changing Mail Delivery Method
    • Configuring IIS Default Pickup Directory
    • Programmatically Changing Delivery Method
  • A Sample Application
  • Summary

Overview

This lesson focuses on how to send mail messages in .NET Framework via a SMTP server. It firstly discusses the techniques which .NET Framework provides you to send mail messages. After that, it discusses types available for you when working with SMTP servers. Next, it discusses how to implement these techniques and to send mails from a .NET client.

At the end of this lesson, there is a sample application, Geming Mail+, which is used to send mails from a various SMTP servers. This application is open-source, so you can download its code freely.

Introduction

Simple Mail Transport Protocol or simply SMTP provides a way for applications to connect to the mail server and send mail messages via server’s exposed SMTP service.

Before .NET 2.0, you were to access SMTP via classes in System.Web.Mail namespace which resides in System.Web.dll library. With the release of .NET 2.0, System.Web.Mail classes became deprecated and replaced with classes in System.Net.Mail namespace which exists in System.dll library. That means that you still can use classes of System.Web.Mail, however, you will receive warnings indicate that those classes are deprecated and you should use classes from System.Net.Mail namespace.

Type Overview

System.Net.Mail Types

System.Net.Mail namespace includes many types each of which provides a special feature. In fact, the most time you will not need to use all of them or to know them at all. However, being aware of what .NET provides to you for accessing SMTP is better to help you evolving your SMTP client application in many sides and in various degrees. Here are the most common classes of System.Net.Mail:

  • SmtpClient:
    One of the essential classes provides you with means of connecting to the SMTP server and sending mail messages. Before starting using this class and send a message, you must initialize server properties like Host, Port, and EnableSsl to allow communicating with the SMTP server. SmtpClient also provides you with some methods like the Send method that sends a specific message synchronously, and SendAsync to send it asynchronously.
  • MailMessage:
    The message to be sent using the SmtpClient class. This class exposes many properties specific to the message like To, CC, Bcc, Subject, and Body properties that corresponds to the message fields.
  • MailAddress:
    Encapsulates a mail address. Provides the DisplayName and Address properties.
  • MailAddressCollection:
    A collection of MailAddress objects. This collection is used inside the MailMessage object in the properties To, CC, and Bcc.
  • Attachment:
    Encapsulates an attached file.
  • AttachmentCollection:
    A collection of Attachment objects. Used in the MailMessage class in its Attachments property.
  • SmtpException:
    Represents an exception thrown from the SmtpClient if it failed to send a message. Use SmtpException’s StatusCode property to determine the error occurred. In addition, see the inner exception for more details.
  • SmtpFailedRecipientException and SmtpFailedRecipientsException:
    Represent exceptions thrown when the SmtpClient fails to send a message to a specific recipient or a group of recipients. Both classes are derived from SmtpException.
  • SmtpPermission and SmtpPermissionAttribute:
    If you are aware of your code running from various locations or from an unsecure environment, you can use these classes to control how your application should access SMTP servers. You use SmtpPermission to control application permissions imperatively. SmtpPermissionAttribute is used to control the permissions declaratively. Consult MSDN documentation for more information about these types and how to use them.

In addition, System.Net.Mail includes various enumerations each represents a set of options for a specific feature. For example, MailPriority enumeration is exposed via the Priority property of a MailMessage object; it can take one of three values, Low, Normal, and High, and it is used to mark your message with a specific priority flag.

System.Web.Mail Types

Besides types in System.Net.Mail, for whose interested in .NET 1.0 and descendent before .NET 2.0, we will cover types of System.Web.Mail briefly. In fact, they are very few types, actually, they are only three classes and three enumerations, and they serve the same as types in System.Net.Mail.

Classes in System.Web.Mail:

  • SmtpMail:
    Serves the same as System.Net.Mail.SmtpClient. However, it exposes only a single property SmtpServer. Plus, it exposes methods for sending mail messages.
  • MailMessage:
    Encapsulates message related information and data like To, CC, BCC, Subject, and Body fields.
  • MailAttachment:
    Encapsulates an attachment. MailMessage exposes a list of MailAttachment objects via its Attachments property.

Besides those only three classes, System.Web.Mail also includes three enumerations, MailEncoding, MailFormat, and MailPriority. I think that those enumerations have expressive names enough and do not need to be explained. If you need some explanation consult MSDN documentation or continue reading this article. Although, this article concentrates on types from System.Net.Mail, they are very similar to the types in System.Web.Mail.

SMTP Servers

In order to connect to a SMTP server you need to be aware of four things:

  • Server address:
    Like smtp.example.com.
  • Port number:
    Usually 25, and sometimes 465. Depends on server’s configuration.
  • SSL:
    You need to know if the server requires a SSL (Secure Socket Layer) connection or not. To be honest, most servers require SSL connections.
  • Credentials:
    You need to know if the server accepts default credentials of the user or requires specific credentials. Credentials are simply the username and password of the user. All e-mail service providers require specific credentials. For example, to connect to your Gmail’s account and send mails via Gmail’s SMTP server, you will need to provide your mail address and password.

The following is a list of some of the major e-mail service providers who provide SMTP services for their clients:

Name Server Address Port SSL Required? 
Live smtp.live.com 25 Yes
Gmail smtp.gmail.com 25 or 465 Yes
Yahoo! plus.smtp.mail.yahoo.com 465, 25, or 587 Yes
Only for Plus! accounts. Consult Yahoo! documentation for more help about selecting the right port number.
GMX mail.gmx.com 25 No

Acrobat.com

Implementation

The following is a simple code segment uses classes from System.Net.Mail namespace to send mail messages via GMX’s SMTP server.

Visit GMX; one of the leader internet mail service providers.

Do not forget to add a using statement (Imports in VB.NET) for the System.Net.Mail namespace.

    // C# Code

    MailMessage msg = new MailMessage();

    // Your mail address and display name.
    // This what will appear on the From field.
    // If you used another credentials to access
    // the SMTP server, the mail message would be
    // sent from the mail specified in the From
    // field on behalf of the real sender.
    msg.From =
        new MailAddress("example@GMX.com", "Example");

    // To addresses
    msg.To.Add("friend_a@example.com");
    msg.To.Add(
        new MailAddress("friend_b@example.com",
            "Friend A"));

    // You can specify CC and BCC addresses also

    // Set to high priority
    msg.Priority = MailPriority.High;

    msg.Subject = "Hey, a fabulous site!";

    // You can specify a plain text or HTML contents
    msg.Body =
        "Hello everybody,<br />" +
        "<br />" +
        "I found an interesting site called " +
        "<a href=\"http://JustLikeAMagic.WordPress.com">" +
        "Just Like a Magic</a>. Be sure to visit it soon.";
    // In order for the mail client to interpret message
    // body correctly, we mark the body as HTML
    // because we set the body to HTML contents.
    msg.IsBodyHtml = true;

    // Attaching some data
    msg.Attachments.Add(new Attachment("C:\\Site.lnk"));

    // Connecting to the server and configuring it
    SmtpClient client = new SmtpClient();
    client.Host = "mail.gmx.com";
    client.Port = 25;
    client.EnableSsl = false;
    // The server requires user's credentials
    // not the default credentials
    client.UseDefaultCredentials = false;
    // Provide your credentials
    client.Credentials =
        new System.Net.NetworkCredential(
            "example@GMX.com", "buzzwrd");

    // Use SendAsync to send the message asynchronously
    client.Send(msg);
    -------------------------------------------

    ' VB.NET Code

    Dim msg As New MailMessage()

    ' Your mail address and display name.
    ' This what will appear on the From field.
    ' If you used another credentials to access
    ' the SMTP server, the mail message would be
    ' sent from the mail specified in the From
    ' field on behalf of the real sender.
    msg.From = _
        New MailAddress("example@GMX.com", "Example")

    ' To addresses
    msg.To.Add("friend_a@example.com")
    msg.To.Add( _
        New MailAddress("friend_b@example.com", _
        "Friend A"))

    ' You can specify CC and BCC addresses also

    ' Set to high priority
    msg.Priority = MailPriority.High

    msg.Subject = "Hey, a fabulous site!"

    ' You can specify a plain text or HTML contents
    msg.Body = _
        "Hello everybody,<br />" & _
        "<br />" & _
        "I found an interesting site called " & _
        "<a href=""http:'JustLikeAMagic.WordPress.com"">" & _
        "Just Like a Magic</a>. Be sure to visit it soon."
    ' In order for the mail client to interpret message
    ' body correctly, we mark the body as HTML
    ' because we set the body to HTML contents.
    msg.IsBodyHtml = True

    ' Attaching some data
    msg.Attachments.Add(New Attachment("D:\Site.lnk")) 

    ' Connecting to the server and configuring it
    Dim client As New SmtpClient()
    client.Host = "mail.gmx.com"
    client.Port = 25
    client.EnableSsl = False
    ' The server requires user's credentials
    ' not the default credentials
    client.UseDefaultCredentials = False
    ' Provide your credentials
    client.Credentials = _
        New System.Net.NetworkCredential( _
            "example@GMX.com", "buzzwrd")

    ' Use SendAsync to send the message asynchronously
    client.Send(msg)

Changing Mail Delivery Method

You can specify that messages sent do not go to the SMTP server. Instead, it is sent to a directory in your computer that you specify. Actually, it is a good idea when it comes to testing your application. Thus, decreases the testing time.

SmtpClient supports two properties for changing mail delivery location; they are DeliveryMethod and PickupDirectoryLocation properties. DeliveryMethod specifies the delivery method that would be taken when sending the message. This property is of type SmtpDeliveryMethod enumeration; therefore, it can be set to one of three values:

  • Network: (default)
    The message is sent via the network to the SMTP server.
  • PickupDirectoryFromIis:
    The message is copied to the mail default directory of the Internet Information Services (IIS).
  • SpecifiedPickupDirectory:
    The message is copied to the directory specified by the property PickupDirectoryLocation.

Configuring IIS Default Pickup Directory

To change the IIS default pickup directory in IIS 7 follow the following steps:

  1. Start Internet Information Services (IIS) 7 Manager.
  2. From the Home view, select SMTP E-mail item. Figure 1 shows the SMTP E-mail item in the IIS 7 MMC snap-in.

    Figure 1 - Selecting SMTP E-mail Item in IIS 7

    Figure 1 - Selecting SMTP E-mail Item in IIS 7

  3. From the SMTP E-mail configuration view, change the default pickup directory by choosing the option “Store e-mail in pickup directory” and selecting your desired directory using the Browse button. Figure 2 shows the SMTP E-mail view while changing pickup directory options.

    Figure 2 - Configuring SMTP E-mail Pickup Directory

    Figure 2 - Configuring SMTP E-mail Pickup Directory

  4. From the right pane, click Apply to save your current settings.

Programmatically Changing Delivery Method

The following lines change the delivery location to a specific location in the drive C. You can add the following lines before the line that calls Send() method of the SmtpClient.

In order for the example to run correctly, the specified directory must be existed or you will receive an exception when executing the Send() method.

    // C# Code
    client.DeliveryMethod =
        SmtpDeliveryMethod.SpecifiedPickupDirectory;
    client.PickupDirectoryLocation = "C:\\mails";

    ----------------------------
    ' VB.NET Code
    client.DeliveryMethod =
        SmtpDeliveryMethod.SpecifiedPickupDirectory
    client.PickupDirectoryLocation = "C:\mails"

A Sample Application

Geming Mail+ is an application that is used to send mails via extendable variety of SMTP servers. This application created using .NET 2.0 and Visual Studio 2008. The following are snapshots of the application:

Geming Mail+ Splash Geming Mail+

Download the application here

Download the source code Here

Summary

This lesson was a great introduction to e-mail programming in .NET Framework. You learned how to send mails via a SMTP server. Soon we will cover how to receive mails in .NET Framework.

Have a nice day…

Fix & Optimize Your Windows