Tuesday 28 May 2013

How to send email using gmail credential in asp.net using c#.

Introduction:-

In this article . I have explained how to send email using Gmail credential in asp.net. Using Gmail credential , you have required your gmailid and gmail password for sending a meil to someone. There are also antother way to send mail using SMTP server in asp.net , but using SMTP server only emailId required for sending email.
 
Design page like this:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        From :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        To :
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        Subject :<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <br />
        Body :<asp:TextBox ID="TextBox4" runat="server" Height="39px"
            TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>

</html>

Don't forget to add following namespace in .cs page.

using System.Net.Mail;

Code Behind Page:-

protected void Button1_Click(object sender, EventArgs e)
    {
        
            MailMessage mail = new MailMessage();
            mail.To.Add(TextBox2.Text);
            mail.From = new MailAddress(TextBox1.Text);
            mail.Subject = TextBox3.Text;

            string Body = TextBox4.Text;
            mail.Body = Body;

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
            smtp.Credentials = new System.Net.NetworkCredential
                 ("youremailid@gmail.com", "gmailpasword");
            //Or your Smtp Email ID and Password
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }

    }

Run the code and test.
If any query regarding this article , feel free to ask.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.