Saturday, 21 July 2012

Send mail using GMail SMTP

  

try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    bool isAllowed = SPContext.Current.Web.AllowUnsafeUpdates;
                    SPContext.Current.Web.AllowUnsafeUpdates = true;
                    SmtpClient smtp;
                    MailMessage mail = new MailMessage();
                    string FromEmail = "s.sugunthan.mca@gmail.com";
                    string EmailPwd = "password";
                    smtp = new SmtpClient("smtp.gmail.com");
                    smtp.UseDefaultCredentials = true;
                    smtp.Host = "smtp.gmail.com";
                    smtp.Port = 587;
                    smtp.Credentials = new System.Net.NetworkCredential(FromEmail, EmailPwd);
                    smtp.EnableSsl = true;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    mail.Body = "Sample Content";
                    mail.To.Add(new MailAddress("sugunthan@gmail.com"));
                    mail.From = new MailAddress(FromEmail);
                    //Bybass the certifiate check
                    ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
                    smtp.Send(mail);
                    SPContext.Current.Web.AllowUnsafeUpdates = isAllowed;
                    ClearFields();
                    Clear_ErrorMsg();
                    lblResult.ForeColor = Color.Green;
                    lblResult.Text = "Mail Send Successfully!!";





                });
            }
            catch (Exception)
            {
                lblResult.ForeColor = Color.Red;
                lblResult.Text = "Sorry! Please Try Again!!";
            }