Attaching files from Stream using FileUpload Control
Author:Mudassar Khan
Here’ I’ll explain how to attach files to email without saving them on the disk
You can refer my articles on how to send emails in
Send-Email-using-CSharp.aspx
and Send-Email-using-VBNet.aspx
When the File is uploaded using FileUpload Control the file is received in the httppostedfile
property.
To attach the HttpPostedFile to the email. You will need to convert it to Stream.
The code below attaches a posted file to email. Note that txtAttachment is a FileUpload control
<asp:FileUpload ID="txtAttachment" runat="server" />
C#
if (txtAttachment.PostedFile != null)
{
try
{
string strFileName =
System.IO.Path.GetFileName(txtAttachment.PostedFile.FileName);
Attachment attachFile =
new Attachment(txtAttachment.PostedFile.InputStream, strFileName);
mm.Attachments.Add(attachFile);
}
catch
{
}
}
VB.Net
If txtAttachment.PostedFile IsNot Nothing Then
Try
Dim strFileName As String = System.IO.Path.GetFileName(txtAttachment.PostedFile.FileName)
Dim attachment As New Attachment(txtAttachment.PostedFile.InputStream, strFileName)
mm.Attachments.Add(attachment)
Catch
End Try
End If
You can download the source code here.
EmailWithAttachment.zip (4.28 kb)