Friday 24 January 2014

Send Email using Asp.net c#

Today i will explain about how to send email using asp.net c# in simple method ..
this method send mail using smtp server.
the design section shown below:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="emailto" runat="server"></asp:TextBox> 
        <asp:Button ID="submit" runat="server" Text="send mail" 
            onclick="submit_Click" />
       
        <br />
        <asp:Label ID="statustxt" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
Add this one first to the page    
using System.Text;
   public bool send_mail(string to, string from, string subject, string body)
       {
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(from,to);
        msg.Subject = subject;
        System.Net.Mail.AlternateView view;
        System.Net.Mail.SmtpClient client;
        StringBuilder msgText = new StringBuilder();
        msgText.Append(" <html><body><br></body></html> <br><br><br>" + body);
        view = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");
        client = new System.Net.Mail.SmtpClient();
        msg.AlternateViews.Add(view);
       
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.Credentials = new System.Net.NetworkCredential("your email address", "email password");
        client.EnableSsl = true;
        client.Send(msg);
        bool k = true;
        return k;
     }
        
    protected void  submit_Click(object sender, EventArgs e)
    {
        try
        {
             string to =emailto.Text;
            string From = "your email address";
            string subject = " Your Email Subject ";
            string Body = "Hello <br>welcome to dreamtheweb<br> Ths is a test mail from dreammtheweb.com ";
           
            Body += "<br><br> please visit http://dreamtheweb.com";
             Body += "<br><br>Thanks! <br>Jishnu chandran";
            bool result = send_mail(to, From, subject, Body);
            if (result == false)
            {
                statustxt.Text = "Mail sent successfully to" + emailto.Text;
            }
            else
            {
                statustxt.Text = "enter your correct mail id";
            }
        }
        catch
        {

            statustxt.Text = "Please check your internet connection";

        }

    }
In email address and password section you enter the corresponding email address and email password . 
After execute the above code you get email .ie in this format  

0 comments:

Post a Comment