How to Send Emails with Attachments

There are 4 steps to send an email with attachments.
 
Step 1
 
image1.jpg

Step 2 

 image2.jpg

Step 3

image3.jpg 
 
Take 3 text boxes and change the ID as TextBox_name, TextBox_email, TextBox_sub, TextBox_body and 1 fileupload control, 1 button, 1 label for message and thereafter take 4 RequiredFieldValidators and validate it with the respective text boxes and fileupload controls.
 
Now double click on button. It will generate click event automatically.
 
After this write this code on the Default.aspx.cs
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.Net.Mail;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        try

        {

            //===============================================//

            MailMessage mail = new MailMessage();

            mail.To.Add(TextBox_email.Text);

            mail.From = new MailAddress("[email protected]");

            mail.Subject = TextBox_sub.Text;

            mail.Body = TextBox_body.Text;

            mail.IsBodyHtml = true;

            Attachment file = new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName);

            mail.Attachments.Add(file);

            SmtpClient smtp = new SmtpClient();

            smtp.Host = "smtp.gmail.com";

            smtp.Port = 587;

            smtp.EnableSsl = true;

            smtp.Credentials = new System.Net.NetworkCredential("youremail", "yourpassword");

            smtp.Send(mail);

            Label6.Text = "Email to " + TextBox_email.Text + " has been send successfully";

 

            //======================================================//

        }

        catch(Exception ex)

        {

            Label6.Text = ex.Message;

        }

    }

}

 

Or you can write this code on click event of button 
 

MailMessage mail = new MailMessage();

mail.To.Add(TextBox_email.Text);

mail.From = new MailAddress("sender's email");

mail.Subject = TextBox_sub.Text;

mail.Body = TextBox_body.Text;

mail.IsBodyHtml = true;

Attachment file = new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName);

mail.Attachments.Add(file);

SmtpClient smtp = new SmtpClient();

smtp.Host = "smtp.gmail.com";

smtp.Port = 587;

smtp.EnableSsl = true;

smtp.Credentials = new System.Net.NetworkCredential("sender's email", "sender's password");

smtp.Send(mail);

Label6.Text = "Email to " + TextBox_email.Text + " has been send successfully";

 
Note - please write your own email , password  replace by sender's email and sender's password.

image4.jpg
 
And run this code and enjoy
Next Recommended Reading Send Email Using Gmail SMTP