Looking into the code, it looks like you want to send email from Gmail. So you first need to do the following steps:
- Go to https://myaccount.google.com/security
- Enable 2-Step Verification
- Click on App passwords and add a new App, let's say "MySampleApp" and generate a password for it. Copy the password (it's 16 characters without any space).
- Then you can use this password from sending email on behalf of yourself.
Now you can use the following code to send email:
using (var client = new SmtpClient())
{
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("YOU@GMAIL.COM", "APP_PASSWORD");
using (var message = new MailMessage(
from: new MailAddress("YOU@GMAIL.COM", "YOUR NAME"),
to: new MailAddress("THEM@ANYWHERE.COM", "THEIR NAME")
))
{
message.Subject = "Hello from code!";
message.Body = "Loremn ipsum dolor sit amet ...";
client.Send(message);
}
}