Monday, March 28, 2011

Source Code to send simple e-mail in asp.net

Create user interface  for sending the mail.  
email.aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="email.aspx.cs" Inherits="email" %>
<html>
<head runat="server">
    <title>E-mail sending program</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table width="100%" border="2">
    <tr>
        <td style="height: 40px; width: 55px;">
                 <asp:Label ID="Label3" runat="server" Text="From"></asp:Label></td>
        <td style="height: 40px"><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
             <td>
                 &nbsp;<asp:Label ID="Label1" runat="server" Text="TO"></asp:Label></td>
             <td>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
                <td style="height: 28px">
            <asp:Label ID="Label2" runat="server" Text="Subject"></asp:Label></td>
        <td style="height: 28px">
            &nbsp;<asp:TextBox ID="TextBox3" runat="server" ></asp:TextBox></td>
        </tr>
        <tr>
            <td style="height: 54px">
            </td>
            <td style="height: 54px">
                &nbsp;<asp:TextBox ID="TextBox4" runat="server" Height="56px"  TextMode="MultiLine"></asp:TextBox></td>
        </tr>
        <tr>
        <td></td>
        <td>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label></td></tr>
        </table></div>
    </form>
</body>
</html>
Its design view will be :



 Code behind page:
email.aspx.cs  page
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;

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 m = new MailMessage(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text);
        try
        {
            NetworkCredential n = new NetworkCredential("yourEmailId","YourPassword");
            SmtpClient s = new SmtpClient("smtp.gmail.com", 587);
            s.EnableSsl = true;
            s.UseDefaultCredentials = false;
            s.Credentials = n;
            s.Send(m);
            Label4.Text = "send" ;
        }
        catch(Exception e1)
            {
                Label4.Text = "Enabled to send"+e1;
            }

    }
}


Here i am using gmail smtp server and its port. you can use own smtp server, If you have own smtp server.

No comments:

Post a Comment