asp.net-coresmtp

How to use SMTP in ASP.NET Core


I'm developing an ASP.NET Core project and get an error when using SMTP.

This is my current code:

string code = GenerateRandom6DigitString();
string subject = "Your Verification Code";

string body = $"Welcome to website!!!\n\nYour verification code is: **{code}**.\n\nPlease enter this code to verify your account.\n\nThank you!";

string myEmail = Environment.GetEnvironmentVariable("EMAIL_ADDRESS") ?? string.Empty;
string myEmailPassword = Environment.GetEnvironmentVariable("EMAIL_PASSWORD") ?? string.Empty;
string mySmtpHost = Environment.GetEnvironmentVariable("SMTP_HOST") ?? string.Empty;

MailMessage mail = new MailMessage();
mail.From = new MailAddress(myEmail);
mail.To.Add(email);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = false;

SmtpClient smtpClient = new SmtpClient(mySmtpHost, 587)
        {
            Credentials = new NetworkCredential(myEmail, myEmailPassword),
            EnableSsl = true,
            UseDefaultCredentials = false,
            DeliveryMethod = SmtpDeliveryMethod.Network,
        };

try
{
    smtpClient.Send(mail);

    lock (lockVerifyValueDict)
    {
        verifyValueDict.Add(email, code);
    }

    return true;
}
catch (Exception ex)
{
    Console.WriteLine($"Failed to send email. Email: {email} Error: {ex.Message}");
    return false;
}

And env file is as following:

EMAIL_ADDRESS=myname@gmail.com
EMAIL_PASSWORD=password
SMTP_HOST=smtp.gmail.com

But I can't send any mail using this code.

In my opinion, it's because of google security settings.

If anybody know about google security settings for smtp, please help me.

Thank you.


Solution

  • You doesn't have to enable anything specific in GMail. In case you're using 2FA you must create an app password which you can do here. I tested it on my own account with MailKit using the following code:

    using MimeMessage message = new();
    message.From.Add(InternetAddress.Parse("myAddress@gmail.com"));
    message.To.Add(InternetAddress.Parse("targetAddress@gmail.com"));
    message.Subject = "Message send from C#";
    
    using SmtpClient client = new();
    await client.ConnectAsync("smtp.gmail.com", 587);
    await client.AuthenticateAsync("myAddress@gmail.com", "The pwd or app pwd");
    await client.SendAsync(message);