Click here to Skip to main content
Full site     10M members (39.7K online)    

Sending Mails in .NET Framework

This article is available in my blog too, check it out here.

اقرأ النسخة العربية من هذا الموضوع هنا. 

شاهد شرح فيديو لهذا الموضوع. 

Contents

Contents of this article:

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:

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:

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:

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 465, 25, or 587  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

Implementation

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

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@gmail.com", "Example");

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

    // 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 = "smtp.gmail.com";
    client.Port = 578;
    client.EnableSsl = true;
    // 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");
    client.DeliveryMethod = SmtpDeliveryMethod.Network;

    // 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@gmail.com", "Example")

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

    ' 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 = "smtp.gmail.com"
    client.Port = 578
    client.EnableSsl = True
    ' The server requires user's credentials
    ' not the default credentials
    client.UseDefaultCredentials = False
    ' Provide your credentials
    client.Credentials = New System.Net.NetworkCredential("example@gmail.com", "buzzwrd")
    client.DeliveryMethod = SmtpDeliveryMethod.Network


    ' 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:

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+

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… 

 
You must Sign In to use this message board.
Search 
Per page   
QuestionSMTP use Proxy connection
a_quu_a
24 Oct '12 - 16:57 
i want to create some code to send email in my office , but the connection use proxy .. i searched any reference, i found that SMTP port and HTTP port is different , so the HTTP Proxy can't allow the process from SMTP. can you give me another reference from this case ? thanks alot
GeneralMy vote of 5
Alaa S. Al Agamawi
8 May '12 - 8:28 
It just solved my problem. Thank you.
QuestionVerifying email addresses
Mike Angelastro
8 Mar '12 - 8:22 
Hi,
 
Is it possible to verify that an email address actually exists with .NET?
 
thanks,
 
Mike
QuestionSending email with attachment from Windows Froms C# application
madeleindt
21 Feb '12 - 23:58 
Hello All,
 
I am super frustrated at the moment - struggling with something that is supposed to be straight forward and Easy. Cry | :(( Cry | :(( Cry | :((
 
My Windows Forms application is taking a screen dump of a production monitor application and then mailing it hourly as an attachment to the production managers. I created a gmail account for the sending and all managers created gmail accounts for receiving this hourly updated.
 
unfortunately my application keeps on falling over when trying to send the email with error:
"+$exception {"Failure sending mail." System.Exceptio{System.Net.Mail.SmtpException}
 
InnerException {"Unable to connect to the remote server"} System.Exception {System.Net.WebException}
 
InnerException {"No connection could be made because the target machine actively refused it 173.194.69.109:587"} System.Exception {System.Net.Sockets.SocketException}
 
my smtp values stored in my app.config:
host = smtp.gmail.com" />
Username: the email account i created for sending the mails mentioned above : aaa@gmail.com
Password = the gmail account password for the above account.
 
Please please please can anyone assist with my problem. What am i doing wrong or what am i missing.
 
hope to get a reply soonest.
 
Thanks!!!
 

        public void SendEmail()
        {
            try
            {
                string strTo = ConfigurationManager.AppSettings["To"];
                string strFrom = ConfigurationManager.AppSettings["From"];
                string strSubject = ConfigurationManager.AppSettings["Subject"];
                string strBody = ConfigurationManager.AppSettings["Body"];
                string strHost = ConfigurationManager.AppSettings["Host"];
                string strUser = ConfigurationManager.AppSettings["Username"];
                string strPw = ConfigurationManager.AppSettings["Password"];
                string strFileName = "TargetMonitor.jpg";
                string strAttachementPath = Application.StartupPath + "\\Image\\" + strFileName;
                string Body = strBody;
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(strAttachementPath);
                MailMessage mail = new MailMessage();
                       
                mail.From = new MailAddress(strFrom, "Target Monitor");
                mail.To.Add(strTo);
                mail.Subject = strSubject;
                mail.Body = Body;
                mail.Attachments.Add(attachment);
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = strHost;
                smtp.Port = 587;
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(strUser, strPw);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

QuestionGood
Abhishek Sur
9 Oct '11 - 9:10 
It reminds me of my post long back
How to Send Mails from your GMAIL Account through VB.NET or C#. Windows Programming, with a Bit of Customization[^]
 
Yet it is useful, but some images are not loading properly.
Abhishek Sur
Don't forget to click "Good Answer" if you like this Solution.
Visit My Website-->


www.abhisheksur.com

QuestionHow to track bounced emails
sathishmarappan1
26 Jan '11 - 23:28 
Hi,
I'm developing email application using ASP.NET and c#. i have to trace bounced emails and need to store the status report in a database. i need ideas and sample code(if any) for doing this task.
 
Thanks in advance.
AnswerRe: How to track bounced emails
Pardeep singh from Chandigarh
9 Dec '11 - 19:28 
plz give me this code, i'm go to every page of google, but no solution was found, can u help me plzz
GeneralMy vote of 5
JH64
4 Jan '11 - 8:06 
Nice one. I learned a lot.
General[My vote of 1] Download Freezes at 58.8 kb ~ 62 kb
owltiger
30 Jun '10 - 9:36 
Do you have a mirror?
GeneralRe: [My vote of 1] Download Freezes at 58.8 kb ~ 62 kb
Mohammad Elsheimy
1 Jul '10 - 11:04 
Sorry to hear that!!! I'll update all download links tonight and I'll notify you as soon as links updated. Smile | :) Thank you.
Regards,
Mohammad Elsheimy
Technology evangelist from Egypt born in 1991
http://JustLikeAMagic.Wordpress.com


Last Updated 28 Dec 2010 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2013