Sending email through Gmail SMTP server with C#



public int SendMail()
    {
        int i = 0;
        //System.Web.Mail.MailMessage objMsg = new System.Web.Mail.MailMessage();
        try
        {
            // Smtp configuration
            string smtpServer = ConfigurationManager.AppSettings["SmtpServer"];
            int smtpserverport = Convert.ToInt32(ConfigurationManager.AppSettings["smtpserverport"]);
            string userName = ConfigurationManager.AppSettings["FromMailId"];
            string password = ConfigurationManager.AppSettings["FromIdPassword"];
            int Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port Number"]);
            string SMTPserverUserName = ConfigurationManager.AppSettings["SMTPServerUserName"];
            string SMTPserverPwd = ConfigurationManager.AppSettings["SMTPServerPassword"];

            // Mail initialization
            System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();
            mailMsg.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["FromMailId"], "HIHL-1056", System.Text.Encoding.UTF8);
            // mailMsg.mail
            mailMsg.To.Add("From Address");
            mailMsg.Subject = @"XYZ";
            mailMsg.Body = "Body";
            //MailAttachment att = new MailAttachment("C:\\Documents and Settings\\xxx.doc");
            //mailMsg.Attachments.Add(att);
            mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
            mailMsg.IsBodyHtml = true;
            mailMsg.Priority = System.Net.Mail.MailPriority.High;

            //The SMTP requires Authentication so the credentials has to be sent

            System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("Usrename", "password");

            //Add the Creddentials

            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.Port = smtpserverport;
            client.Host = smtpServer;
            client.EnableSsl = false;
            client.UseDefaultCredentials = false;
            client.Credentials = mailAuthentication;
            //client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
            //client.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(client_SendCompleted);
            object userState = mailMsg;
            try
            {
                client.Send(mailMsg);
                //MessageBox.Show("Emailsend successfully");
                i = 1;
                return i;

            }
            catch (System.Net.Mail.SmtpException exx)
            {
                i = 0;
                return i;
            }


        }
        catch (Exception ex)
        {


        }
        return i;
    }



0 comments:

Post a Comment