Pages

Thursday, July 25, 2013

How to Send Email in Asp.net

This article will be explain how to send email in Asp.net. To send email in Asp.net you have to use a namespace "System.Net.Mail".
Step 1
Open "Defaul.aspx" file and following control.
<form id="form1" runat="server">
    <div>
    </div>
        <asp:TextBox ID="FromText" runat="server" style="top: 69px; left: 452px;height: 22px; width: 257px"></asp:TextBox>
        <asp:TextBox ID="ToText" runat="server" style="top: 127px; left: 447px;height: 22px; width: 259px"></asp:TextBox>
        <asp:TextBox ID="SubText" runat="server" style="top: 179px; left: 449px;height: 22px; width: 258px"></asp:TextBox>
        <asp:TextBox ID="MsgText" runat="server" style="top: 231px; left: 454px;height: 148px; width: 252px"></asp:TextBox>
        <asp:Label ID="result" runat="server" style="top: 445px; left: 447px;height: 17px; width: 84px" Text="Label"></asp:Label>
        <asp:Button ID="Button1" runat="server" style="top: 436px; left: 551px;height: 26px; width: 56px" Text="Button" />
    </form>
Step 2
In "Default.aspx.cs" page write following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Drawing;
 
public partial class Email : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage mm = new MailMessage();
 
        SmtpClient smtp = new SmtpClient();
 
        mm.From = new MailAddress(FromText.Text);
 
        mm.To.Add(new MailAddress(ToText.Text));
 
        mm.Subject = SubText.Text;
 
        mm.Body = MsgText.Text;
 
        mm.IsBodyHtml = true;
 
        smtp.Host = "smtp.gmail.com";
 
        smtp.EnableSsl = true;
 
        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
 
        NetworkCred.UserName = "example@gmail.com";//Your email id will be here
 
        NetworkCred.Password = "Your Password";
        smtp.UseDefaultCredentials = true;
 
        smtp.Credentials = NetworkCred;
 
        smtp.Port = 587;
        try
        {
            smtp.Send(mm);
            result.Text = "your message has been sent.....";
            result.ForeColor = Color.Green;
        }
 
        catch (Exception er)
        {
            result.Text = "Error in sendig message";
            result.ForeColor = Color.Red;
        }
    }
}

No comments:

Post a Comment