Here, we will see how can we send email using our Gmail SMTP in c# .NET. Generally, for sending an email from one place to another two parties are required -- first is the sender and the second is the receiver. We will use the Mail Message class of .NET to send an email. For this, we will require a few details:
- Sender Email Address
- Sender Password
- Receiver Email Address
- Port Number
- EnableSSL property
And most important before we start coding we need to import two namespaces to access the MailMessage Class:
- using System.Net;
- using System.Net.Mail;
Note
EnableSSL property generally specifies whether SSL is used to access the specified SMTP mail server or not. Please go through the piece of code to send an email as given below. Nowadays Gmail has become more secure due to various security reasons, so while sending email using mail message class we get the Authentication Error also. Please follow the steps given below to change some settings in Sender Gmail account to get rid of that error.
- using System.Net;
- using System.Net.Mail;
- namespace SendMail {
- class Program {
- static string smtpAddress = "smtp.gmail.com";
- static int portNumber = 587;
- static bool enableSSL = true;
- static string emailFromAddress = "[email protected]";
- static string password = "Abc@123$%^";
- static string emailToAddress = "[email protected]";
- static string subject = "Hello";
- static string body = "Hello, This is Email sending test using gmail.";
- static void Main(string[] args) {
- SendEmail();
- }
- public static void SendEmail() {
- using(MailMessage mail = new MailMessage()) {
- mail.From = new MailAddress(emailFromAddress);
- mail.To.Add(emailToAddress);
- mail.Subject = subject;
- mail.Body = body;
- mail.IsBodyHtml = true;
-
- using(SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)) {
- smtp.Credentials = new NetworkCredential(emailFromAddress, password);
- smtp.EnableSsl = enableSSL;
- smtp.Send(mail);
- }
- }
- }
- }
- }
Follow the below steps to get rid of this error.
- Sign in to your Gmail account and go to settings.
- Go to Account and Import and click on other Google Account settings.
- Then click on
- Turn this ON (Allow less secure app)
Now, run the code and send an email to you dear one .... happy coding :)