Tuesday, April 10, 2012

Modify Mail Settings in web.config programmatically in Asp.net

Add this code in web.config for Mail settings
===================================== system.net
mailSettings
smtp deliveryMethod="Network" from="YourEmailId"
network host="YourHost" password="Yourpassword" port="Yourport"
userName="YourUserName" enableSsl="true"
/smtp
/mailSettings
/system.net
===============================================

 Modify mail settings code MailSettings.aspx.cs
==============================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Net.Mail;
using System.Net.Sockets;
using System.IO;
using System.Web.Configuration;
using System.Configuration;
using System.Net.Configuration;

public partial class Admin_MailSettings : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetCurrentMailSettings();
        }
    }

    public void GetCurrentMailSettings()
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(
             HttpContext.Current.Request.ApplicationPath);
        SmtpSection settings =
            (SmtpSection)config.GetSection("system.net/mailSettings/smtp");

    

        if (settings != null)
        {
            txtUserName.Text = settings.Network.UserName;
            txtPassword.Text = settings.Network.Password;
            txtFromEmail.Text = settings.From;
            txtSmtpHost.Text = settings.Network.Host;
            txtSmtpPort.Text = settings.Network.Port.ToString();


            //if (settings.Network.EnableSsl == true)
            //{
            //    chkSSL.Checked = true;
            //}
            //else
            //{
            //    chkSSL.Checked = false;
            //}
        }


    }

    public void ModifyMailSettings()
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(
        HttpContext.Current.Request.ApplicationPath);
        SmtpSection settings =
            (SmtpSection)config.GetSection("system.net/mailSettings/smtp");
        settings.From = txtFromEmail.Text.Trim();
        settings.Network.UserName = txtUserName.Text.Trim();
        settings.Network.Password = txtPassword.Text.Trim();
        settings.Network.Host = txtSmtpHost.Text.Trim();
        settings.Network.Port = int.Parse(txtSmtpPort.Text.Trim());
      
        //if (chkSSL.Checked)
        //{
        //    settings.Network.EnableSsl = true;
        //}
        //else
        //{
        //    settings.Network.EnableSsl = false;
        //}
       // config.Save();
        config.Save(ConfigurationSaveMode.Modified);
        lblStatus.Visible = true;
        lblStatus.Text = "Mail Settings are Saved Successfully";      
       

    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ModifyMailSettings();
       
    }


    protected void btnTest_Click(object sender, EventArgs e)
    {
        string FromMail=txtFromEmail.Text.Trim();
        string ToMail=txtFromEmail.Text.Trim();
        string SmtpHost = txtSmtpHost.Text.Trim();
        int SmtpPort = int.Parse(txtSmtpPort.Text.Trim());
        string UserName = txtUserName.Text.Trim();
        string Password = txtPassword.Text.Trim();

        try
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(FromMail, ToMail);

            mail.Subject = "Test";
            mail.Body = "Test Mail Settings";

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = SmtpHost;  //Or Your SMTP Server Address
            smtp.Credentials = new System.Net.NetworkCredential(UserName, Password);

            //Or your Smtp Email ID and Password
            smtp.Port = SmtpPort;
            smtp.EnableSsl = true;
            smtp.Send(mail);
            Page.ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript: alert('MailSettings are working properly'); ", true);
            btnSubmit.Visible = false;

            //string msg="Test";
            //bool checkSettings = Check(SmtpHost, SmtpPort,out msg);
            //if (checkSettings == true)
            //{
            //    Page.ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript: alert('MailSettings are working properly'); ", true);
            //    btnSubmit.Visible = true;
            //}
            //else
            //{
            //    Page.ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript: alert('MailSettings are not working properly'); ", true);
            //    btnSubmit.Visible = false;

            //}
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript: alert('MailSettings are not working properly'); ", true);
            btnSubmit.Visible = false;

        }

           

    }

   
        public static bool Check(string host, int port, out string welcomeMessage)
        {
            try
            {
                using (TcpClient smtp = new TcpClient(host, port))
                using (StreamReader reader = new StreamReader(smtp.GetStream()))
                {
                    welcomeMessage = reader.ReadLine();

                    //validate the reasponse
                    if (welcomeMessage.StartsWith("220", StringComparison.InvariantCulture))
                    {
                        //Send QUIT as recommended by RFC 821
                        try
                        {
                            using (StreamWriter w = new StreamWriter(smtp.GetStream()))
                            {
                                w.WriteLine("QUIT");
                                w.Flush();
                                string result = reader.ReadLine();
                            }
                        }
                        catch
                        { }

                        return true;
                    }
                    else
                    {
                        welcomeMessage = "";
                        return false;
                    }
                }
            }
            catch (Exception)
            {
                welcomeMessage = "";
                return false;
            }
        }
  
}


Sending mail using Mail Settings in web.config
====================================

public void sendByGmail(string Empname, string ToAddress, string Subject, string Body, string Sendername)
        {
          
            Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
            MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;

            SmtpSection smtpSection = mailSettings.Smtp;
            //read the from email of the web.config file 
            string fromEmail = smtpSection.From;
            int port = mailSettings.Smtp.Network.Port;
            string host = mailSettings.Smtp.Network.Host;
        //    bool enableSSL = mailSettings.Smtp.Network.EnableSsl;
            string username = mailSettings.Smtp.Network.UserName;
            string password = mailSettings.Smtp.Network.Password;
         

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(fromEmail, ToAddress);

          
            mail.Subject = Subject;
            mail.Body = Body;

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = host;  //Or Your SMTP Server Address
           smtp.Credentials = new System.Net.NetworkCredential(username, password);

            //Or your Smtp Email ID and Password
            smtp.Port = port;
            smtp.EnableSsl = true;
            smtp.Send(mail);

        }

No comments:

Post a Comment