Monday, 2 September 2013

Sending Email with Attachment in Asp.net

1. Open Visual Studio
2. Create a New Website
3. Create Web Page
4. Design UI like below image



5. Add namespaces
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;

6.Write Code on Send Button Click Event

string path = FileUpload1.PostedFile.FileName.ToString();
        try
        {
            MailMessage mail = new MailMessage();
            mail.To.Add(txtto.Text);
            mail.From = new MailAddress("sapna@gmail.com");// your email
            mail.Subject = txtsubject.Text;

            string Body = null;
            Body = txtbody.Text;
            mail.Body = Body;
            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Credentials = new System.Net.NetworkCredential("sapna@gmail.com", "123456");//your email and password
            smtp.EnableSsl = true;
            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            if (File.Exists(path))
            {
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(path);
                mail.Attachments.Add(attachment);
            }
            smtp.Send(mail);
          
        }
        catch (Exception ex)
        {
            ex.ToString();
      
        }


    }

No comments:

Post a Comment

Thanks

SQL server tricky questions