I was working in Visual Studio with Windows Forms. I added a method SendVerificationCode, to send the verification code using System.Net.Mail:
using System.Net.Mail;
namespace PasswordManager
{
public partial class Form1 : Form
{
Random rnd = new();
private void SendVerificationCode(object sender, EventArgs e)
{
if (!(textBox4.Text == "") && !(textBox2.Text == ""))
{
verificationCode = "";
for (int _ = 0; _ < 4; _++)
{
verificationCode += nums[rnd.Next(0, 10)];
}
try
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
mail.From = new MailAddress("**********@gmail.com");
mail.To.Add(textBox2.Text);
mail.Subject = "Verification code";
mail.Body = verificationCode;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("*********@gmail.com", "**********");
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception)
{
throw new Exception("It's not working");
}
}
}
}
}
The textBox2.Text was ********@wp.pl.
It throws an exception "it’s not working".
Can somebody help me?
Thank you.
>Solution :
You’re trying to send from a Gmail address. Gmail no longer allows simple username/password authentication. Until recently you could enable "Less Secure Apps" and get a per-app password, but this is no longer available*. Instead you’ll need to get an OAuth2 token… which is not supported in System.Net.Mail.
That is, you cannot do this with .NET’s built-in SMTP client.
Most people doing serious work have their own SMTP service. But for Gmail, there are third party libraries that can help. MailKit is one example.
* Technically this still available for some types of account, but it shuts off for good on Monday, less than a week from now.