.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Code Snippets >> Email >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

C#.net code for Sending Mail with attachment

Posted By:Pravin       Posted Date: August 04, 2011    Points: 40    Category: Email    URL: http://www.dotnetspark.com  

This is the simple asp.net application for sending mail on button click event.

using System.Net.Mail;
// namespace is required to sendmail

protected void Button1_Click(object sender, EventArgs e)
            string from = "xyz@gmail.com";
            //Replace this with your own correct Gmail Address

            string to = "zyx@anymail.com";
            //Replace this with the Email Address to whom you want to send the mail

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(from, "One Ghost" , System.Text.Encoding.UTF8);
            mail.Subject = "This is a test mail" ;
            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            mail.Body = "This is Email Body Text";
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = true ;
            mail.Priority = MailPriority.High;
            Attachment att1 = new Attachment(@"D:\ABC\Sample.txt");
            SmtpClient client = new SmtpClient();
            //Add the Creddentials- use your own email id and password

            client.Credentials = new System.Net.NetworkCredential(from, "xxxxxxxxxx");

            client.Port = 587; // Gmail works on this port
            client.Host = "smtp.gmail.com";
            client.EnableSsl = true; //Gmail works on Server Secured Layer
            catch (Exception ex) 
            Exception ex2 = ex;
            string errorMessage = string.Empty; 
            while (ex2 != null)
                errorMessage += ex2.ToString();
                ex2 = ex2.InnerException;
            HttpContext.Current.Response.Write(errorMessage );
             } // end try 


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend