Sending mails using ASP.NET

This code works on, both, the main server and the local server. Copy the mentioned code and place it in your .cs file.

protected void btnSubmit_Click1(object sender, EventArgs e)
    {
        string fromMail = string.Empty, host = string.Empty, user = string.Empty, password = string.Empty;
        int port = 0;

        SmtpSection mailSettings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
        if (mailSettings != null)
        {
            fromMail = mailSettings.From;
            host = mailSettings.Network.Host;
            port = mailSettings.Network.Port;
            user = mailSettings.Network.UserName;
            password = mailSettings.Network.Password;
        }
        MailMessage message = new MailMessage();
        message.From = new MailAddress(txtEmail.Text);
        message.Subject = "Feedback Mail";
       message.IsBodyHtml = true;
        message.Body = "Contact Details <br/>" + "<b>Name:</b>" + txtName.Text + " <br/> <b>Email - address :</b>" + txtEmail.Text +
        "<br/> <b>Message :</b>" + txtMessage.Text; ;

        message.BodyEncoding = Encoding.ASCII;

        message.To.Add("your mail id");
        SmtpClient smtp = new SmtpClient(host);
        smtp.Port = port;
        smtp.Credentials = new System.Net.NetworkCredential
        (user, password);
        smtp.Send(message);
        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ASET", "<script type='text/javascript'>alert('Your Message Has Been Send ');</script>", false);
        lbltxt.Text = "Message successfully send";
    }
}

Finally, in Web.config, you place this code:

<system.net>

<mailSettings>

<smtp from="usermail id">

<network host="webmail.smtp.com" port="25" userName=" usermail id " password=" usermail password" defaultCredentials="false"/>

</smtp>

</mailSettings>

</system.net>

Ebook Download
View all
Learn
View all