Tuesday, November 26, 2013

Send email without login in contact us form.

Send email to admin using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Drawing;

using System.Net;
using System.Net.Mail;
using System.Configuration;


namespace SRWS
{
    public partial class Contact : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            { }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                SendMail();
                lblmsz.Text = "Your query has been sent successfully, We'll contact you soon.";
                lblmsz.ForeColor = Color.Green;

                Clear();

            }
            catch (Exception)
            {
                lblmsz.Text = "Your information is not sent.";
                lblmsz.ForeColor = Color.Red;
            }
        }
        protected void SendMail()
        {
            var fromAddress = txte.Text; // fromAddress where you send the mail

            var toAddress = "info@XXXXX.co.in"; // any address where the email will be sending

            const string fromPassword = ""; //Password of your gmail address

            string subject = "Customer Information"; // Passing the values and make a email formate to display
            string body = "Customer Name: " + txtname.Text + Environment.NewLine;
            //body += "Email: " + txte.Text + Environment.NewLine;
            body += "Customer Mobile: " + txtmo.Text + Environment.NewLine;
            body += "Message: " + txtme.InnerText + Environment.NewLine;
            MailMessage mail = new MailMessage();
            mail.To.Add(toAddress);
            mail.IsBodyHtml = true;
            mail.Body = body;

            var smtp = new System.Net.Mail.SmtpClient();// smtp settings
            {
                smtp.Host = "mail.XXXXXX.co.in";
                smtp.Port = 25;
                smtp.EnableSsl = false;
                smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
                smtp.Timeout = 20000;

            }
            // Passing values to smtp object
            smtp.Send(fromAddress, toAddress, subject, body);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Clear();
        }
        public void Clear()
        {
            txtname.Text = " ";
            txtmo.Text = " ";
            txte.Text = " ";
            txtme.InnerText = " ";
        }

    }

}

No comments:

Post a Comment