Click here to Skip to main content
15,881,413 members
Articles / Web Development / HTML

Sending Emails using .NET Part II

Rate me:
Please Sign up or sign in to vote.
4.24/5 (41 votes)
8 May 2006CPOL4 min read 230.4K   103   28
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.

Image 1

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

C#
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

C#
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;
<span style="font-size: 9pt;">  /* create the email message */</span>
 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;
VB
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

  Image 2

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.

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)


Written By
Architect Providence Software
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

 
Generalsending mail Pin
kaustubh85-Mar-11 21:10
kaustubh85-Mar-11 21:10 
GeneralMy vote of 5 Pin
Turner K James17-Dec-10 10:21
Turner K James17-Dec-10 10:21 
GeneralMy vote of 1 Pin
mdunath7-Oct-10 21:58
mdunath7-Oct-10 21:58 
Generalsending email to Outlook distribution lists Pin
stored30-Jan-09 8:30
stored30-Jan-09 8:30 
GeneralRe: sending email to Outlook distribution lists Pin
Sorwen23-Apr-09 7:25
Sorwen23-Apr-09 7:25 
GeneralQuery. Pin
Ashutosh Phoujdar25-Dec-08 19:40
Ashutosh Phoujdar25-Dec-08 19:40 
Generalasp.net 2005 -Sending many emails Pin
Member 44900422-Dec-08 6:35
Member 44900422-Dec-08 6:35 
GeneralNice Article But... Pin
Mohamad Kaifi26-Sep-08 22:02
Mohamad Kaifi26-Sep-08 22:02 
GeneralNewbie question Pin
driansmith14-May-08 11:49
driansmith14-May-08 11:49 
The Web.config file for the VB page

What happens if we do not have a USERID or PASSWORD for the smtp server? What do I use here instead?

Thanks
QuestionSending email using Outlook Pin
Salahuddins11-Jul-07 0:44
Salahuddins11-Jul-07 0:44 
QuestionDon't have Library Pin
jorgesnz31-May-07 18:04
jorgesnz31-May-07 18:04 
AnswerRe: Don't have Library Pin
Prabhakar Manikonda4-Jun-07 2:29
Prabhakar Manikonda4-Jun-07 2:29 
QuestionException while sending mail Pin
vata299920-Mar-07 3:18
vata299920-Mar-07 3:18 
QuestionHow my e-mail don't go to Bulk folder? Pin
vahid shojaei zadeh6-Dec-06 19:35
vahid shojaei zadeh6-Dec-06 19:35 
QuestionRe: How my e-mail don't go to Bulk folder? Pin
abdul78620-Mar-07 1:45
abdul78620-Mar-07 1:45 
GeneralThanks your article really helped ! Pin
HarryBeck233-Sep-06 20:43
HarryBeck233-Sep-06 20:43 
QuestionAnd what about the current Web Page ? Pin
danielclar2-Jun-06 5:53
danielclar2-Jun-06 5:53 
Generalobsolete in .net 2.0 Pin
ksboy16-May-06 6:51
ksboy16-May-06 6:51 
GeneralVery Basic & Outdated Pin
Znose8-May-06 19:34
Znose8-May-06 19:34 
GeneralRe: Very Basic & Outdated Pin
Prabhakar Manikonda8-May-06 20:32
Prabhakar Manikonda8-May-06 20:32 
General[Message Deleted] Pin
D Timmerman8-May-06 4:05
D Timmerman8-May-06 4:05 
GeneralRe: Dull subject Pin
Prabhakar Manikonda8-May-06 20:47
Prabhakar Manikonda8-May-06 20:47 
GeneralRe: Dull subject Pin
Jeff Lindholm11-May-06 3:07
Jeff Lindholm11-May-06 3:07 
GeneralSystem.Web.Mail is deprecated in .NET 2.0 Pin
JeffMiles8-May-06 3:51
JeffMiles8-May-06 3:51 
GeneralRe: System.Web.Mail is deprecated in .NET 2.0 Pin
eggsovereasy8-May-06 10:33
eggsovereasy8-May-06 10:33 

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

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