Sunday, 2 December 2012

send email with attachment using c#


Send email with attachment using C# through gmail.
sending email from C# through gmail
private void Send-EMail-through-Gmail()
{
                try
                {
                    System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587); ;
                    smtpClient.EnableSsl = true;
                    smtpClient.DeliveryFormat = System.Net.Mail.SmtpDeliveryFormat.International;
                    smtpClient.Credentials = new System.Net.NetworkCredential("YourgmailID", "Your gmail password");
                    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                    System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(@"C:\inetpub\wwwroot\Tutorials\CsharpSamples\DateOne.cs");
//just give file name, if u want specific files use System.IO.Stream object,

                    msg.Body="<h1>Pls see this code</h1>";
                    msg.IsBodyHtml=true; //set if your code contains html tags
                    msg.Priority = System.Net.Mail.MailPriority.High;
                    msg.Subject="pls see this code";
                    msg.SubjectEncoding = System.Text.Encoding.UTF8;
                    msg.To.Add("rockandhra.net@gmail.com"); //add as many you want 1 in eachline
                    msg.To.Add("xyz@yahoo.com");
                    msg.From = new System.Net.Mail.MailAddress("your from address","displayname");
                    msg.BodyEncoding = System.Text.Encoding.UTF8;
                 
//reply address in case you need to reply to someother e-mail address
                    msg.ReplyToList.Add("pzpurru@yahoo.com");
                  //attachment
                    msg.Attachments.Add(attachment);
                 

                    smtpClient.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(smtpClient_SendCompleted);
//send e-mail asynchronously delegate will be called once send mail completes.
                    smtpClient.SendAsync(msg, "new e-mail");

                }
                catch (System.Net.Mail.SmtpException EX)
                {
                    Console.WriteLine(EX.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
}
        static void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                    Console.WriteLine(e.Error.InnerException.Message + ":" + e.Error.Message);
                else
                    Console.WriteLine("Message Sent");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

No comments:

Post a Comment