Labels:

In this example i am going to describe how to send email with attachment in ASP.NET using fileUpload Control. I am saving the uploaded file into memory stream rather then saving it on server.And for this example i m using Gmail SMTP server to send mail, this code also works fine with any SMTP Server. For sending Email in ASP.NET , first of allwe need to add Syatem.Net.Mail namespace in code behind of aspx page.

C# Code Behind

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSend_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add(txtTo.Text);
//mail.To.Add("amit_jain_online@yahoo.com");
mail.From = new MailAddress(txtFrom.Text);
mail.Subject = txtSubject.Text;
mail.Body = txtMessage.Text;
mail.IsBodyHtml = true;

//Attach file using FileUpload Control and put the file in memory stream
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("YourGmailID@gmail.com", "YourGmailPassword");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);

}
}

VB.NET Code Behind

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net.Mail

Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim mail As New MailMessage()
mail.[To].Add(txtTo.Text)
'mail.To.Add("amit_jain_online@yahoo.com");
mail.From = New MailAddress(txtFrom.Text)
mail.Subject = txtSubject.Text
mail.Body = txtMessage.Text
mail.IsBodyHtml = True

'Attach file using FileUpload Control and put the file in memory stream
If FileUpload1.HasFile Then
mail.Attachments.Add(New Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName))
End If
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
'Or Your SMTP Server Address
smtp.Credentials = New System.Net.NetworkCredential("YourGmailID@gmail.com", "YourGmailPassword")
'Or your Smtp Email ID and Password
smtp.EnableSsl = True

smtp.Send(mail)
End Sub
End Class