How to Send Mail Through Asp.Net Using C#
Sending email is a basic task in Asp.Net. In classic ASP, we worked with the CDONTS object to send emails from an ASP page. The Smtp class in ASP .NET provides methods for sending mail messages.In this article, we will see, how can we send email from an ASP .NET page.
1. Open Visual Studio > File > New > Website.
2. Now Right click on your website name in Solution Explorer > Add New Item > WebForm and click on OK.
3. Now take two textbox for name and email field.Now designer part will look like this.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table align="center"> <tr> <td> Name</td> <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Email</td> <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td> </tr> <tr> <td colspan="2"> <asp:Button ID="Button1" runat="server" Text="Send Mail" /> </td> </tr> </table> </div></form> </body> </html>
4. Add following namespaces on coding page.
using System.Net.Mail; using System.Net.Security;
5. Now on button click event add following code.
MailMessage mail = new MailMessage(); mail.From = new MailAddress("demo@gmail.com"); mail.To.Add("yourmail@domain.com"); //to send mail on textbox value use this code. mail.To.Add(TextBox2.Text); mail.IsBodyHtml = true; mail.Subject = "Form"; mail.Body = "<br><br>Someone want to contact you <br>" + "<b>Name:</b>" + TextBox1.Text + " <br/> <b>Email :</b>" + TextBox2.Text + "; SmtpClient smtp = new SmtpClient("smtp.gmail.com",587); smtp.Credentials = new System.Net.NetworkCredential("demo@gmail.com", "password_here"); smtp.EnableSsl = true; smtp.Send(mail);
Enjoy….