Follow by Email

Saturday, 24 November 2012

How to Send Email in Asp.Net







ASPX Page:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
  <asp:Label ID="Label1" runat="server" Text="To : "></asp:Label>
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <asp:TextBox ID="to_txt" runat="server" Width="200px"></asp:TextBox>
  <br /><br />
  <asp:Label ID="Label2" runat="server" Text="Subject :"></asp:Label>
  &nbsp;&nbsp;&nbsp;
  <asp:TextBox ID="subject_txt" runat="server" Width="200px"></asp:TextBox>
  <br />
  <br />
  <asp:Label ID="Label3" runat="server" Text="Message :"></asp:Label>
  <br />
  <asp:TextBox ID="message_txt" runat="server" Height="117px"
  TextMode="MultiLine" Width="279px"></asp:TextBox>
  <br />
  <br />
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
  Text="Send Mail" />
  <br />
  <asp:Label ID="Label4" runat="server" Text="Label"></asp:Label>
 </div>
 </form>
</body>
</html>
 
CodeBehind Page:
 
 
using System;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
   protected void Button1_Click(object sender, EventArgs e)
 {
    try
  {
   MailMessage mail = new MailMessage();
   SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

   mail.From = new MailAddress("your-email-address@gmail.com"); //you have to provide your gmail address as from address
   mail.To.Add(to_txt.Text );
   mail.Subject = subject_txt.Text ;
   mail.Body = message_txt.Text ;

   SmtpServer.Port = 587;
   SmtpServer.Credentials = new System.Net.NetworkCredential("gamil-username", "gmail-password"); //you have to provide you gamil username and password
   SmtpServer.EnableSsl = true;

   SmtpServer.Send(mail);
   Label4.Text = "Email successfully sent.";
  }
  catch (Exception ex)
  {
   Label4.Text = "Email Failed." + ex.Message;
  }
 }
}
 

0 comments:

Post a Comment


                                                            

 
Design by Abhinav Ranjan Sinha