Monday, May 7, 2012

How to send mail with attachment using C# .Net...

      using System.Net;
       using System.ComponentModel;
       using System.Net.Mail;

        protected void Page_Load(object sender, EventArgs e)
        {
                SendEmail();
        }

        private void SendEmail()
        {
             System.Net.Mail.MailMessage mailmessage = new MailMessage();

             string from = "sender@gmail.com";         //The Email id of sender
             string pass = "senderpass";        //password of sender
            string to="receiver@gmail.com";        //Email id of Receiver

            string subject="Hello This is Test Message.";  //Subject of mail
            string body = "This is code for Email sending";  //body of mail
            mailmessage.From = new MailAddress(from,"Kartik");
            //mailmessage.To.Add(Email);//if you are sending mail to  multiple  users then combine all users emailid with comma
            mailmessage.To.Add(to);
            mailmessage.Subject = subject;
            mailmessage.Body = body;
            Attachment attachment = new Attachment(Server.MapPath("test.txt")); //create the attachment
            mailmessage.Attachments.Add(attachment);    //add the attachment
            mailmessage.IsBodyHtml = true;//make it true if you are using the StringBuilder Class

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);//port no and domain name will be different as per the Email domain
            client.Credentials = new NetworkCredential(from, pass);
            client.EnableSsl = true;
            client.Send(mailmessage);
           
            //this is the code for if you want to send the mail asynchronously replace with above line Client.Send(mailmessage)....

            /*
            client.SendCompleted += new SendCompletedEventHandler(mail_SendCompleted);
           
            client.SendAsync(mailmessage, null);
            */
        }

        void mail_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
                Console.WriteLine("Message cancelled");
            else if (e.Error != null)
                Console.WriteLine("Error: " + e.Error.ToString());
            else
                Console.WriteLine("Message sent");
        }

0 comments:

Post a Comment