How to send email using Gmail SMTP Mail Server in ASP.Net


In this article I will explain how to send email using Gmail SMTP Server in ASP.Net. To send email with Gmail SMTP Server, you will need to use an email address and password of a valid Gmail account .

Step-1:- Create Web Form to send Email.with some fields such as Recipient Email address, Subject, Body, Attachment, Gmail account email address, Gmail account password and a Button to send the email.


Step-2:- Go to security settings at the following link https://www.google.com/settings/security/lesssecureapps and enable less secure apps . So that you will be able to login from all apps

Step-3:- write this code to Send email using Gmail SMTP Account on send button .

using System.IO;
using System.Net;
using System.Net.Mail;

protected void SendEmail(object sender, EventArgs e)
    {
        using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
        {
            mm.Subject = txtSubject.Text;
            mm.Body = txtBody.Text;
            if (fuAttachment.HasFile)
            {
                string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
                mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
            }
            mm.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
        }
    }

No comments:

Post a Comment

Xamarin Android Project App

Xamarin Android Project App 1. Xamarin -- Make a CALCULATOR Android App   https://drive.google.com/open?id=0B8OPCXLrtKPmWC1FWWtFM2lraVk...