Sunday, December 2, 2012

Send Email in C# using Gmail.


For sending email you need a Email server. You can buy your own email server or you can use Gmail for this purpose. Gmail allows you to send emails through their email server.


private void Sendmail()
        {
            string From = "YourMail@gmail.com"; // Your email address
            string To = "ToMail@gmail.com"; // receivers email
            string Yourpassword = "xxxxx"; //Your email password
            MailMessage Mail = new MailMessage();
            Mail.To.Add(To);
            Mail.From = new MailAddress(From, "Test Group", System.Text.Encoding.UTF8);
            Mail.Subject = "Testing Email";
            Mail.SubjectEncoding = System.Text.Encoding.UTF8;
            Mail.Body = "This is Email Body!";
            Mail.BodyEncoding = System.Text.Encoding.UTF8;
         
            Mail.IsBodyHtml = true;
            Mail.Priority = MailPriority.High;
            SmtpClient Client = new SmtpClient();
            Client.Port = 587;
            Client.Host = "smtp.gmail.com";
            Client.Credentials = new System.Net.NetworkCredential(From, Yourpassword);
            Client.EnableSsl = true;
            try
            {
                Client.Send(Mail);
                MessageBox.Show("mail sent");
            }
            catch (Exception ex)
            {
                Exception ex2 = ex;
                string errorMessage = string.Empty;
                while (ex2 != null)
                {
                    errorMessage += ex2.ToString();
                    ex2 = ex2.InnerException;
                }
           
                MessageBox.Show(errorMessage);
            }
       }

No comments:
Write comments
Recommended Posts × +