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

52 comments:

  1. Nice,, thanks for sharing ...

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

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

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

    ReplyDelete
  5. @Aashish : Unbeatable champ Of Gaming :

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

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

    ReplyDelete
  7. 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.

    ReplyDelete
  8. 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?

    ReplyDelete
  9. 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!

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

    ReplyDelete
  11. how to fill dataset with sqladapter with parameters thanks

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

    ReplyDelete
  13. nice i want to open my own blog how i do

    ReplyDelete
  14. Very Helpful:)
    -Prashant

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

    ReplyDelete
  16. 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?

    ReplyDelete
  17. nice tutorial.
    thanks sir.

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

    ReplyDelete
  19. The remote certificate is invalid according to the validation procedure.

    ReplyDelete
  20. @Above : plz check ur system date and correct it

    ReplyDelete
  21. 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?

    ReplyDelete
  22. Chiuki Chuki Nice Handsome

    ReplyDelete
  23. 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

    ReplyDelete
  24. @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");

    ReplyDelete
  25. 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

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

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

    ReplyDelete
  28. ya its working thanks a lot.......

    ReplyDelete
  29. Great article very useful

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

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

    ReplyDelete
  32. Hi
    This code is very nice

    ReplyDelete
  33. 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

    ReplyDelete
  34. 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

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

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

    ReplyDelete
  37. Thank u very much for writing useful article.

    ReplyDelete
  38. 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

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

    ReplyDelete
  40. Dear,

    Got it., Thanks., Great man

    Manoj kumar T

    ReplyDelete
  41. 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

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

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

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

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

    ReplyDelete
  45. 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

    ReplyDelete