Click here to Skip to main content
Click here to Skip to main content

Sending Emails using .NET Part II

, 8 May 2006
Rate this:
Please Sign up or sign in to vote.
Use ASP.NET 2.0 new library System.web.mail to send emails

Introduction

Sending email is becoming a minimum requirement for any web application in these days. Microsoft Visual Studio .Net 2005 aimed to reduce the code we write. Which results the birth of numerous powerful packages.Here I will show three approaches for this,

1) System.web.mail ASP.NET 1.1

2) System.net.mail ASP.NET 2.0 and

3) Using Microsoft Outlook

Note That the above three methods can only send email. To read email you either need a Mime parsing component such as aspNetMime or a POP3 component such as aspNetPOP3
 

Before You Start

If you are not a using ASP.NET 2.0 then you can do it using DotNetOpenMail.dll API, which I had discussed in my previous article Sending Emails using .NET Part I please go through it if you are not using ASP.NET 2.0. Check if the Microsoft SMTP Server is turned on. To do this either open the Internet Services Manager directly or open Computer Management and Navigate to Internet Information Services -> Default SMTP Virtual Server and checkout if the button with the 'play' icon on it is disabled, that means it is already started.

  The SmtpServer property This mail will by default be sent through the local SMTP server. You can specify a different SMTP server, by setting the SmtpServer string property on the SmtpMail class. Since SmtpMail is a static class and SmtpServer is a shared static property, once this property has been set, it will be used for all other calls to the SmtpMail.Send method, even in different web applications.

1) System.Web.Mail

The System.Web.Mail namespace has three classes.

  • SmtpMail
  • MailMessage
  • MailAttachment
The SmtpMail is a static class. That is, we do not need to instantiate an object from this class. That is, this class is Ready Made; you can directly invoke the methods as it is static
System.Web.Mail.SmtpMail.Send ("senderID@domainName.com",
     "receiverID@domainName.com","Subject of the Mail”, 
     ” Message Body"); 
//Using Namespaces that are to be included for email feature is 
 
  Using System.Web.Mail;
 
Five Easy Steps to create and Send emails            
Step 1: Create a MailMessage object
Step 2: Set the to, from, subject properties of MailMessage
Step 3: Set the BodyFormat to MailFormat.Html or Text,
Step 4: Set the Body Text for the MailMessage
Step 5: Send the MailMessage using SmtpMail.send method
Using SmtpMail class is very simple the below code will let you know this fact.
                       
/* Step 1*/
//               C#.NET CODE <% @Page Language="C#" %>
                 <% @Import Namespace="System.Web.Mail" %>
               <%
                 MailMessage message = new MailMessage ();
/* Step 2*/
                 message. To = "receiverID@domainName.Com";
                 message. From = "sender@domainName.com";
                 message. Subject =   "Email Subject";
/*Step 3*/
                 message.BodyFormat = MailFormat.Html; 
/*Step 4*/
                 msgMail.Body = "<html><body><h2" + 
                                " align = center>Hello World!" + 
                                " </h2></body></html>";
/*Step 5*/
                 SmtpMail.Send (message);
                 Response. Write ("Email Sent");
             %> 

                                                   VB.NET Code

 
/*Step 1*/                              
              <%@Page Language="VB" %> 
              <% @Import Namespace= "System.Web.Mail" %>
 
          <%
              Dim message As MailMessage
              message = New MailMessage ()
/*Step 2*/ 
              message. To = "receiverID@domainName.Com"
              message. From = "sender@domainName.com"
              message. Subject = "Email Subject"
/*Step 3*/
              message.BodyFormat = MailFormat.Html
/*Step 4*/
              msgMail.Body = "<html><body><h2 " + 
                             "align = center>Hello World! " + 
                             "</h2></body></html>";
/*Step 5*/
              SmtpMail.Send (message)
              response. Write ("<BR><font color=red" + 
                               " face=verdana size=2> " + 
                               "Sent the mails. </font>")
           %>

Attaching The Files to your Message

Here is the sample code to attach a sample text file
  MailAttachment attachment1 =
   new MailAttachment (@"c:\My Documents\OfficeFile1.doc");
  // Add Another One...
  MailAttachment attachment2 = 
   new MailAttachment ("d:\\Documents\\asp.netTurorial.doc");
  message.Attachments.Add (attachment1);
  message.Attachments.Add (attachment2);
  SmtpMail.Send (message);

2) Using System.Net.Mail [ASP.NET 2.0]

For the users who are using ASP.NET 1.1 System.Web.Mail will work but it is deprecated in current version. We can say that System.Net.Mail is the replacement of System.Web.Mail as it comes with more features such as authentication, that is from what domain name and with what user id the use is sending the emils. This is done using System.Net.NetworkCredential as you will see in below code. The System.Net.Mail namespace contains the SmtpClient and MailMessage Classes that we need in order to send the email and specify the user credentials necessary to send authenticated email.

                                                 C#.NET CODE

 The Using Statement

 using System.Net.Mail;

  /* create the email message */
 MailMessage message = new MailMessage("senderID@domainName.com",
     "receiverID@domainName.com","subject of the Message ",
     "body fo the message ");

/* create and add the attachment(s)*/
Attachment attachment = new Attachment("sample.doc",
                        MediaTypeNames.Application.Octet);
  message.Attachments.Add(attachment);

/* create SMTP Client and add credentials */
SmtpClient smtpClient = new SmtpClient("Your SMTP Server");
smtpClient.UseDefaultCredentials = false;
  /* Email with Authentication */
smtpClient.Credentials = new NetworkCredential("userID", 
                         "password", "domainName");

/*Send the message */
smtpClient.Send(message);

                                                       VB.NET CODE

The Using Statement
imports System.Net.Mail;
Dim message As New MailMessage("senderID@domainName.com",_
    "receiverID@domainName.com","subject of the Message ",_
    "body fo the message ")
/* create and add the attachment(s) */
Attachment attachment = new Attachment("sample.doc",
                        MediaTypeNames.Application.Octet)
  message.Attachments.Add(attachment)

/* create SMTP Client and add credentials */
Dim emailClient As New new SmtpClient("Your SMTP Server")

  /* Email with Authentication */
Dim SMTPUserInfo As New new NetworkCredential("userID", "password", "domainName")
emailClient.UseDefaultCredentials = False
emailClient.Credentials = SMTPUserInfo

/*Send the message */
emailClient.Send(message)

 The Web.config file 

 <?xml version="1.0"?>
  <CONFIGURATION> 
   <SYSTEM.NET> 
        <MAILSETTINGS>
          <SMTP from="authicationEmailID@yourdomain.com"> 
           <NETWORK password="password" 
                 userName="UserID" port="25" 
                 host="smtp.yourdomain.com"/>   
          </SMTP> 
        </MAILSETTINGS> 
     </SYSTEM.NET> 
  </CONFIGURATION>  

There are other properties that you can set, such as the message priority, whether it should be text or HTML, and the encoding type. More information about these additional properties should be available in the ASP.Net framework documentation. Note That the Send method do not have return values about the success of dispatching the email message. The reason for this is that the emails simply are written into the Pickup folder of the Inetpub directory from where they are read and then sent by the SMTP Service. Failed emails (dispatching errors) also are written into files, and moved to Badmail folder.

3) Using Microsoft Outlook

  Using Microsoft Outlook is ingeneral not preferable but just discussing the possible ways of sending emails. Take a look at it.

Step 1: Add a reference to the Outlook library

 

Step 2: import the Outlook namespace:

 Imports Outlook 
Step 3: Then, add code to create a new MailItem and set its properties to the information which is already known. Finally, display the MailItem. Here’s the complete code
'Create Outlook application.
   OutlookApplication = New Outlook. Application
'Create Outlook MailItem
   Dim message As MailMessage message = New MailMessage () 
   message. To = "receiverID@domainName.Com" 
   message. From = "sender@domainName.com" 
   message. Subject = "Email Subject"
 
   OutlookMailItem = CType (OutlookApplication.CreateItem (
                            OlItemType.olMailItem), message)
 
'Display MailItem.
   OutlookMailItem.Display ()

Using Outlook is easy but the programmer is the ultimate judge to decide what approach is to be used in his application.

Conclusion

Microsoft .NET is extremely powerful and yet simple to work with. I Hope that you will get a basic understanding of how to create and send email's with ASP.NET 2.0 simple and compact code.
H A P P Y C O D I N G . . .

History

Version 1.0 Release 2006

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Prabhakar Manikonda
Architect IBM Sandton South Africa
South Africa South Africa
Prabhakar Manikonda
MS CS, M.A SW, MCSD.NET, MCTS Sharepoint 2007, 3.0 Services
 

 
Proven track record with seeing successful projects through to completion. Excellent team player and completer-finisher. Specialist in methodology, architecture,object-oriented design, and project management. Plan and manage workload, monitoring and resolving programming issues Transform requirements into architectural, Publishes white papers and articles in software development and runs software consulting & recruiting

Comments and Discussions

 
QuestionDon't have Library Pinmemberjorgesnz31-May-07 18:04 
AnswerRe: Don't have Library PinmemberPrabhakar Manikonda4-Jun-07 2:29 
QuestionException while sending mail Pinmembervata299920-Mar-07 3:18 
QuestionHow my e-mail don't go to Bulk folder? Pinmembervahid shojaei zadeh6-Dec-06 19:35 
QuestionRe: How my e-mail don't go to Bulk folder? Pinmemberabdul78620-Mar-07 1:45 
GeneralThanks your article really helped ! PinmemberHarryBeck233-Sep-06 20:43 
QuestionAnd what about the current Web Page ? Pinmemberdanielclar2-Jun-06 5:53 
Generalobsolete in .net 2.0 Pinmemberksboy16-May-06 6:51 
GeneralVery Basic & Outdated PinmemberZnose8-May-06 19:34 
GeneralRe: Very Basic & Outdated PinmemberPrabhakar Manikonda8-May-06 20:32 
General[Message Deleted] PinmemberD Timmerman8-May-06 4:05 
GeneralRe: Dull subject PinmemberPrabhakar Manikonda8-May-06 20:47 
GeneralRe: Dull subject PinmemberLorad11-May-06 3:07 
GeneralSystem.Web.Mail is deprecated in .NET 2.0 PinmemberJeffMiles8-May-06 3:51 
GeneralRe: System.Web.Mail is deprecated in .NET 2.0 Pinmembereggsovereasy8-May-06 10:33 
GeneralRe: System.Web.Mail is deprecated in .NET 2.0 PinmemberPrabhakar Manikonda8-May-06 20:32 
GeneralRe: System.Web.Mail is deprecated in .NET 2.0 PinmemberPrabhakar Manikonda8-May-06 20:41 
GeneralRe: System.Web.Mail is deprecated in .NET 2.0 PinmemberJeffMiles9-May-06 3:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 8 May 2006
Article Copyright 2006 by Prabhakar Manikonda
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid