Monday, March 3, 2008

ASP.Net Sending E-mail Attachment

Sending E-mail Attachment

Let us now look at how to include attachments to our e-mail. Open the web-page in design mode and add an HTML file upload control to the form. Set it to run at Server, and switch to code-behind to make changes in our previous method.

Dim msg As New Net.Mail.MailMessage(
_txtFrom.Text,
_txtTo.Text,
_txtSubject.Text,
_txtMessage.Text)
If fileUpload.PostedFile.FileName = "" Then
Else
msg.Attachments.Add( _
New System.Net.Mail.Attachment _
(fileUpload.PostedFile.FileName))
End If

All you need to do is check if the user posted a file or not, and if he did, then you need to create a new Net.Mail.Attachment object and add that to the MailMessage Object's Attachments collection. The line of code doing that could be broken down into the following, for simplicity;

Dim strName As String = fileUpload.PostedFile.FileName
Dim myAttachment As System.Net.Mail.Attachment
myAttachment = New Net.Mail.Attachment(strName)
msg.Attachments.Add(myAttachment)

No comments: