Tuesday, April 10, 2012

Send Mail using ASP.NET

Sending mail using ASP.NET/C# - using Gmail SMTP.

In ASP.NET you use SMTP protocol for sending email . SMTP stands for Simple Mail Transfer Protocol . ASP.NET uses System.Net.Mail namespace for sending mail . You need to instantiate SmtpClient class and assign values to the Host and Port. For SMTP default port is 25 and it can vary for different Mail Servers. In the following example I have used Gmail address to send mail

The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587.

Following is code to send mail using ASP.NET/C#:

Design:


Code:

You need to include the following namespaces:
using System.Net.Mail;
using System.Net;

protected void btnSend_Click(object sender, EventArgs e)
    {
        const string FromAddress = "gmail id";//For Example:hello@gmail.com
        string Subject = txtsubject.Text;
        String Body = txtMail.Text;
        MailMessage mail = new MailMessage();
        mail.To.Add(txtTo.Text);
        mail.From = new MailAddress(FromAddress);
        mail.Subject = Subject;
        mail.Body = Body;
        mail.Priority = System.Net.Mail.MailPriority.High;
        SmtpClient mclient = new SmtpClient();
        mclient.Credentials = new System.Net.NetworkCredential(FromAddress,
        "gmail id password");
        mclient.Port = 587; // Gmail works on this port
        mclient.Host = "smtp.gmail.com";
        mclient.EnableSsl = true; //Gmail works on Server Secured Layer

        try
        {
            mclient.Send(mail);
        }
        catch (Exception error)
        {
            throw error;
        }

    }

No comments:

Post a Comment