<a href="http://www.micropoll.com/akira/mpview/585320-168921">Click Here for Poll</a><a href="http://www.questionpro.com" title="online surveys">Online Survey</a><BR> | <a href="http://www.micropoll.com" title="Website Polls">Website Polls</a><BR> | <BR><a href="http://www.micropoll.com/akira/MicroPoll?mode=html&id=168921">View MicroPoll</A></div>

Visual Studio 2010!

Read now >

Windows Mobile Development Thoughts

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

ADVERTISEMENT
Sending E-Mail from .Net Applications
By Peter Aitken

Rate This Article: Add This Article To:

Given the importance and wide use of E-mail, it's essential for developers to be able to implement E-mail functionality in their applications. The tools available in the .Net framework make this an easy task.

In case you haven't noticed, E-mail has become an extremely popular means of communication. Spam aside (don't get me started on spam!), there are innumerable legitimate uses for E-mail. From the .Net developer's perspective, there are also many situations in which you would like to send E-mails under program control. Sending E-mail messages from programs is nothing new, but this is yet another area in which the .Net framework has simplified the programmer's life.

.Net lets you send E-mail from both desktop applications and from Web-based applications (ASP.NET). There are plenty of situations where both would be useful. On the desktop, an application can check your Customers database and send customized messages to each contact, or it could use the information in your Invoices database to send reminders to past due accounts. On the web side of things, you can easily implements an E-mail based confirmation system to people who register on your site. I am sure that you have seen these in use: when you register, the server sends you a confirming E-mail with your password and other information. I could go on and on but I am sure you have you own uses for these techniques.

Classes for creating and sending E-mails are located in the System.Web.Mail namespace. The techniques for sending messages from a Web or a desktop application are essentially the same.

At the heart of .Net's mail capabilities is the SMTPServer class, which represents exactly what its name says—the SMTP server that will be used to send your message. What I like about this class is that you can set its ServerName property to use a specific mail server, or leave this property alone to use whatever server is available locally. Then, the simplest way to send a quick and dirty E-mail is with the Send() method:

SMTPServer.Send(fromAddress, toAddress, subject, messageText)

The arguments, all strings, provide the four essential parts of any E-mail message. This works just fine, but does not provide access to some commonly used E-mail features such as carbon copies and attachments. I'll get to that in a minute, but first let me mention that code for sending messages should always be protected in a Try...Catch block because errors are most definitely possible.

When you want to get a little more sophisticated with your messages, use the MailMessage class. This too is part of the System.Web.Mail namespace, and it provides a full set of tools for making use of all the options that modern E-mail systems offer. The MailMessage constructor takes no argument so you must set its properties after creating an instance. Those properties that are used frequently are described here:

  • Attachments: A collection of attachments that are sent with the message.
  • Bcc: A semicolon-delimited list of E-mail addresses that receive a blind carbon copy of the message.
  • Body: The body of the message.
  • BodyFormat: Set to MailFormat.HTML if the message body is in HTML format or to MailFormat.Text if it is in plain text format.
  • Cc: A semicolon-delimited list of E-mail addresses that receive a copy of the message.
  • From: The E-mail address of the sender.
  • Priority: The priority of the message. Set to MailPriority.High, MailPriority.Low, or MailPriority.Normal.
  • Subject: The message subject line.
  • To: A semicolon-delimited list of E-mail addresses that receive the message.

Using the MailMessage class, code to assemble and send a message might look like this. This assumes that the referenced text boxes exist for the user to enter the message information.

Dim MyMessage as New MailMessage()
 With MyMessage
   .To = txtTo.Text
   .Cc = txtCc.Text
   .From = txtFrom.Text
   .Subject = txtSubject.Text
   .Body = tstBody.Text
   .Priority = MailPriority.High
 End With

 ' The next line needed only if not using the default
 ' local SMTP server.
 SmtpMail.SmtpServer = "Mailserver.wherever.com"
 try
   SmtpMail.Send(MyMessage)
   MsgBox("Your email message has been sent.")
 catch e as Exception
   Msgbox("There was an error sending the message: " & e.ToString)
 end try

To format your message with HTML, simply include the desired HTML tags in the body and set the BodyFormat property accordingly:

MyMessage.Body = "<html><body><p><b>Happy birthday!</b> and many
    happy returns.</p></body?</html>"
 MyMessage.BodyFormat = MailFormat.HTML

Adding attachments is just a bit more involved. First you must create a MailAttachment object that represents the file being attached. Next you add this object to the MailMessage object's Attachments property (which is really a collection). Here's how to add two attachments to a message:

Dim FileToAttach1 
  As New MailAttachment("<a href="file:///c:/data/catalog.pdf">c:\data\catalog.pdf</a>")
Dim FileToAttach2 
  As New MailAttachment("<a href="file:///c:/data/catalog.pdf">c:\data\sales.xls</a>")
MyMessage.Attachments.Add(FileToAttach1)
MyMessage.Attachments.Add(FileToAttach2)

E-mail capability can be taken to another level by wrapping it in a Web service. This has several potential advantages that may apply in your situation:

  • The web service can be used by all computers on the network. You need enable SMTP service on only one machine.
  • The service can be used by non-.Net programs, such as those written in Visual Basic, Java, etc.
  • The service can be used by programs running on operating systems other than Windows.

You'll have to define an XML data structure for sending the E-mail information. Here's one way it could be done:

<E-mailMessages>
    <E-mailMessage>
        <From></From>
        <To></To>
        <Cc></Cc>
        <Bcc></Bcc>
        <Subject></Subject>
        <Body></Body>
        <Attachments>
            
<Attachment></Attachment>
</Attachments>
</E-mailMessage>
</E-mailMessages>

Save the XML template as a text file. Then, an application that will use the service would include code like the following (you'll need to include the relevant XML namespaces in your project, or course):

Dim MailXML As new XmlDocument()
 ' Load the XML template.
 MailXML.Load("EMailTemplate.txt")
 ' Put data in the elements.
 MailXML.SelectSingleNode("//From").InnerText = "someone@somewhere.com"
 MailXML.SelectSingleNode("//To").InnerText = "someperson@overthere.net"
 MailXML.SelectSingleNode("//Subject").InnerText = ".Net mail"
 MailXML.SelectSingleNode("//Body").InnerText = "Sent using a web service!"
Dim MailProxy As New MailService()
 MailProxy.Url = "http://server.com/MailService/MailService.asmx"
 MailProxy.SendMail(oDoc.OuterXML)

In this example, MailService is the name of the proxy class generated when you add a reference to the E-mail web service to your project. SendMail is the web service method that extracts the data from the request, creates the message, and sends it.

Given the importance and wide use of E-mail, it's essential for developers to be able to implement E-mail functionality in their applications. The tools available in the .Net framework make this an easy task.




Discuss Sending E-Mail from .Net Applications
 
This has really helped me to send mail via c#.net 3.5. Thanks
>>> Post your comment now!
 

 
 
>>> More ASP and .Net Coding Techniques Articles          >>> More By Peter Aitken