Send Email With Attachment In Asp.Net

This example shows how to Send Email With Attachment In Asp.Net 2.0,3.5,4.0 C# And VB.NET Using FileUpload Control. I am saving the uploaded file into memory stream rather then saving it on server.

Send Email With Attachment in Asp.Net
For this example i m using Gmail SMTP server to send mail, this code also works fine with any SMTP Server.

For sending E-mail, first of all we need to add Syatem.Net.Mail namespace in code behind of aspx page. 

In my previous article i describe how to send mail using gmail in asp.net 

Create the page as shown in the image above, put textbox for message and FileUpload Control for adding the file attachment.

Write following code in click event of Send button in Code behind of page

C#
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
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

Build and run the application to test the code

If you like this post than join us or share

52 comments:

ASP.NET,C#.NET,VB.NET said...

nice artical its very good


Unknown said...

thz bro!


ராமகிருஷ்ணன் த said...

well, useful


Anonymous said...

Nice,, thanks for sharing ...


C# Tutorial said...

Nice tutorials, check out my C Sharp video tutorials they are pretty awesome!


kunji said...

well,nice


Deepak Kumar said...

Very Very Very Thanks//
Thanks allot.
wow great working..


Aashish : Unbeatable champ Of Gaming said...

when i tried to send a mail on yahoo account....above code failed.


Unknown said...

@Aashish : Unbeatable champ Of Gaming :

Hi aashish, i've checked the code and it's working with yahoo accounts as well


Nirmal Kumar said...

Thanks...Its Working.....thanks for your help


U.R.Pratibha said...

Hi,
Can you please help me with a snippet of code, to verify if the email address exists or not, without sending mail.

Expecting ur reply.

Thanks in advance.


U.R.Pratibha said...

Hi,
i needed a snippet of code to verify the email, if it exists or not, but without sending mail... can you pls help me with this?


ASP.NET Code Snippets said...

Thanks for the tutorial, make sure to check out my <a href="http://www.freecodesnippets.com/code/asp.net>ASP.Net Code Snippets</a> too!


b4u said...

Thanks....very useful........


Anonymous said...

Thanks a Lot Buddy.you have really done a good Job.
Keep Sharing Knowledge


OnClick Web Solutions said...

how to fill dataset with sqladapter with parameters thanks


namrata said...

thank you so much...i was searching 4 this...
thanx once again


rahul said...

nice i want to open my own blog how i do


Anonymous said...

Very Helpful:)
-Prashant


Rajesh said...

wow great improvement in blog visitors .... and congrats
from
Funevil


Unknown said...

i Want this application in vb6 and not for web application but in windows application and my pc name is sys11 and server name is maulik than how can i do it?


Anonymous said...

nice tutorial.
thanks sir.


asp dot net developers said...

Thanks a ton for this great share. It was really helpful. Keep sharing similar stuff.


Anonymous said...

The remote certificate is invalid according to the validation procedure.


Unknown said...

@Above : plz check ur system date and correct it


jenifa said...

hi amit,
Really nice sharing..ur blog is too good..
while am running this application am getting run time error as
"The specified string is not in the form required for an e-mail address."
can u please help me to solve this?


Anonymous said...

Chiuki Chuki Nice Handsome


Anonymous said...

Hello Amit , Please guide me how i can fix " email to send " text field , for example i want to remove TO SEND EMAIL text box and fix to send email only at one ID ...

always email send to only one ID webmaster@domain.com


Unknown said...

@Above: Delete the To textBox from aspx page and write below mentioned code

Remove this line

mail.To.Add(txtTo.Text);

and add this line of code
mail.To.Add(" webmaster@domain.com");


Anonymous said...

Thanks , Respectable Sir, please can you guide me how i can write the text at XML through aspx, inquiry form ?

Example , i want to write rss file using web page form ?

and this week i red your posts its really nice easy and Chuki Chuki , if you have skype and yahoo and msn please write thanks


PHP Development said...

How the same will be done in PHP? This is all about to send email with attach. but what about PHP?


Anonymous said...

Thank you for the work you have done into this post, this helps clear up a few questions I had.


Anonymous said...

ya its working thanks a lot.......


Anonymous said...

Great article very useful


Anonymous said...

The application works but I can't see the attachment file was it send?


Anonymous said...

What about the attachment file I could not see it after sending?


Anonymous said...

Hi
This code is very nice


Anonymous said...

Hi
please help me
i am using visual studio 2005 and sql server 2005
i want simple code when user log In after login
user can see his profile it's ok...
but how to update profile of the login user
please guide me .

Regard
Rames


Anonymous said...

Anonymous said... Hi

I put this in a test page and it works great! I'm trying to get it to work in a usercontrol (ascx) but the file is never attached. Will this work for a usercontrol?

Thanks
Larry

June 29, 2011 7:40 PM


Sumeet said...

This code will work on for gmail accounts for sending and receiving.....but still i liked it...... nice work..


Unknown said...

excellent work..it is so very useful..keep posting...keep rocking..tanx..!!


Anonymous said...

its good .


Anonymous said...

good article..


Gandharv said...

Thank u very much for writing useful article.


Anonymous said...

Dear,
While running your code., i got there is an error message like.,
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required" in
line, smtp.Send(mail);

ur suggestion pls.,

Manoj kumar T


Unknown said...

@manoj: have you uses correct gmail username and password ?


Anonymous said...

Dear,

Got it., Thanks., Great man

Manoj kumar T


Anonymous said...

Dear Amit,

If i want to send email from Gmail account to some other domain(yahoo, in, hotmail lie.,) in the sense, what are the modifications i need to change?

Manjo kumar T


Unknown said...

@manoj: You don't need any changes to send email to other domains

refer Send email using gmail in asp.net for more info


Anonymous said...

Hello! Just want to say thank you for this interesting article! =) Peace, Joy.


Unknown said...

You can also send emails with live account with smtp.live.com and server port is 25. I tested it worked for me.


Anonymous said...

hi ,I have got an error
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 173.194.79.108:25
what to do


Find More Articles