This article will teach us how to send emails through the .Net C# code. Common issue while sending an email.
Below is the code to send an email.
Host: smtp.gmail.com
Port: 587
var client = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("senderemal@gmail.com", "password"), EnableSsl = true }; client.Send("senderfromemail@gmail.com", "to@gmail.com", "test", "testbody");
var client = new SmtpClient("smtp.gmail.com", 587){Credentials = new NetworkCredential("senderemal@gmail.com", "password"),EnableSsl = true};client.Send("senderfromemail@gmail.com", "to@gmail.com", "test", "testbody");
You will get the below error while running this code.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication
Upto last year's user, you can enable Less secure app access from Google account settings and run the code. But, now Google no longer supports third-party apps on the devices. Google disables the Less secure app access option.
To fix this issue, you need to create an app password from the google account settings.
Step 1: Go to your Google Account.
Step 2: Select Security.
Step 3: Under "Signing in to Google," select App Passwords.
If the select App password option is unavailable, this means you have not enabled 2-Step verification.
Step 4: Enable the 2-Step verification first.
Step 4: Enable the 2-Step verification first.
Step 5: Click on the app password and generate your new password. Select the device and choose the device you’re using and then Generate.
The App Password is the 16-character code in the yellow bar on your device.
Tap Done.
Step 6: Use your new password in the same code.
var client = new SmtpClient("smtp.gmail.com", 587){Credentials = new NetworkCredential("senderemal@gmail.com", "apppassword"),EnableSsl = true};client.Send("passfromemail@gmail.com", "to@gmail.com", "Subject", "Email body");
You can find, your email is working
If you want to send an email with HTML Content the use below code.
If you want to send an email with HTML Content the use below code.
var body = "Email body here.<br/><br/> <a>Reset password</a>"; var msg = new MailMessage(); msg.IsBodyHtml = true; msg.Body = body; msg.Subject = "Subject here"; msg.From = new MailAddress("fromemail@gmail.com"); msg.To.Add("toemail@gmail.com"); client.Send(msg);
I hope you like the article.
Helpful!
ReplyDelete