AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=913&pId=-1
Sending E-mails with Attachments using ASP.NET 2.0
page
by Rich Crawford
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 35865/ 48

Introduction

Download Sample Code

In this article we will look at two demonstrations for sending e-mail messages with attachments in ASP.NET 2.0. 

In earlier versions of ASP.NET (1.0 and 1.1), we used the System.Web.Mail class to send e-mail messages.  ASP.NET 2.0 replaced the System.Web.Mail class with the new and improved System.Net.Mail class.

The System.Web.Mail class uses the System.Web.Mail.SmtpMail class to handle the actual delivery of the e-mail message.  This has also been replaced by a new class (System.Net.Mail.SmtpClient) for the System.Net.Mail class. 

Sending attachments is just as simple in the new class as it was in the old.  What excites me about the new class is the ability to use attachments by filename or contentstream.  The latter of the two comes in very handy.

Attachments are handled by the System.Net.Mail.Attachment and System.Net.Mail.AttachmentCollection classes.  We will see how these are used in the following demonstrations.

Adding attachments by filename

Attaching by filename is the simplest way to add an attachment because it requires the least amount of code.  This works best when you know the location and name of the file you wish to attach.

In this demonstration we will create a new System.Net.Mail.MailMessage to send our e-mail message.  We will be attaching an existing file by filename.  

Listing 1 - Attaching a file by filename

Sub SendMail()
  'Configure basic infomation for an e-mail message
  Dim FromName As String = "Sam Poole"
  Dim FromEmail As String = "sample@yourdomainname.com"
  Dim Subject As String = "Sample Email with attachment"
  Dim ToName As String = "Sam Poole"
  Dim ToEmail As String = "sample@yourdomainname.com"
  Dim FileName As String = Server.MapPath("./files/samplefilename.pdf")
 
  'Create the SmtpClient object  (assumes using localhost)
  Dim smtp As New System.Net.Mail.SmtpClient("127.0.0.1")
 
  'Create the MailMessage object
  Dim msg As New System.Net.Mail.MailMessage()
 
  'Assign from address
  msg.From = New System.Net.Mail.MailAddress(FromEmail, FromName)
 
  'Assign to address
  msg.To.Add(New System.Net.Mail.MailAddress(ToEmail, ToName))
 
  'assign subject, and body
  msg.Subject = Subject
  msg.Body = "This is a test message with an attachment"
 
  msg.Attachments.Add(New System.Net.Mail.Attachment(Filename))
  'Send the message with SmtpClient
  smtp.Send(msg)
End Sub
Adding attachments by contentstream

Attaching by contentstream is a little more involved than attaching by filename, but I have found that it is not always practical to store the file on the file system.  This is where the contentstream comes in handy. 

The contentstream is a System.IO.Stream object.  You may use any readable stream as the contentstream.  A file uploaded using the FileUpload webcontrol allows you to access the PostedFile.InputStream.  This means that you can read the file directly out of the InputStream and avoid having to save to disk in order to attach it to a message. 

Simple Scenario

You want to make a simple WebForm that allows your students to submit a simple e-mail message with a file attachment to submit a term paper.  Since the attachment is being sent via e-mail to a recipient, there is no need for you to store the attachment on the file system.

To achieve this, I would simply make a WebForm with the appropriate fields.

Figure 1 - WebForm for message

<img width=355 height=355 src="/ArticleFiles/913/image001.gif">

The listing does not include any error checking and also assumes that the student will be uploading a MS Word document.  I kept this short and sweet for demonstration purposes, but it is functional.

Listing 2 - Attaching a file with contentstream

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
                            Handles Button1.Click
 
  Dim msg As New System.Net.Mail.MailMessage()
  Dim smtp As New System.Net.Mail.SmtpClient("127.0.0.1")
  Dim fromadx As New System.Net.Mail.MailAddress("sample@yourdomain.com""Term
  Paper Mailer")
  Dim toadx As New System.Net.Mail.MailAddress("recipient@yourdomain.com",
  "Professor Plumb")
  msg.From = fromadx
  msg.To.Add(toadx)
  msg.Subject = txtSubject.Text
  msg.Body = txtBody.Text
   If FileUpload1.HasFile = True Then
     msg.Attachments.Add(New
     System.Net.Mail.Attachment(FileUpload1.PostedFile.InputStream, "Final Term
     Paper.doc"))
   End If
  smtp.Send(msg)
End Sub

Another good use for the contentstream attachment is when the file exists in a byte() array.  The byte() data can be put into a System.IO.MemoryStream which is then readable by the attachment object.

I have used that technique with SQL database image fields.

Listing 3 - MemoryStream example

'Assumes you have a datatable with SQL image data in it.
Dim ms as new System.IO.MemoryStream(Table1.rows(0).item("ImageFieldName"))

The MemoryStream now contains the contents of the image data from Table1.  It can be read by the System.Net.Mail.Attachment object.

References
Conclusion

The new mail class in ASP.NET 2.0 offers many enhancements over pervious versions.  The most recent real-world application I have applied this to involves creating a new PDF document from an IRS W-9 PDF form, populating the form fields from a database record and then e-mailing the form to the recipient to print and sign.

This article provided a brief demonstration on how to send e-mail messages in ASP.NET with file attachments using both filename and contentstream options.  I hope you find it useful.

Download Sample Code


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-24 8:59:15 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search