Home > Software design >  ASP.NET CORE - Send email: Please log in via your web browser and then try again
ASP.NET CORE - Send email: Please log in via your web browser and then try again

Time:01-22

I am trying to send a mail in Production with a verification link for a user registration.

For this, I have attached the credentials of the gmail account that sends the mail in my appsettings.json

APPSETTINGS.JSON:

appsettings.json

The action of my controller that sends the mail is the following:

   [HttpPost]
    public async Task<JsonResult> Register(AddUserViewModel model)
    {
        if (ModelState.IsValid)
        {
            User user = await _userHelper.AddUserAsync(model, imageId);

            if (user == null)
            {
                return Json("Email repeat");
            }

            string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);
            string tokenLink = Url.Action("ConfirmEmail", "Account", new
            {
                userid = user.Id,
                token = myToken
            }, protocol: HttpContext.Request.Scheme);

            Response response = _mailHelper.SendMail(model.Username, "App - Confirmación de cuenta", $"<h1>App - Confirmación de cuenta</h1>"  
                $"Para habilitar el usuario, "  
                $"por favor hacer clic en el siguiente enlace: </br></br><a href = \"{tokenLink}\">Confirmar Email</a>");

            if (response.IsSuccess)
            {
                return Json("Email send");
            }
          
            string message = response.Message;
            return Json(message);
           
        }

        return Json("Model invalid");
    }

The sendEmail method that returns a Response is as follows:

 public Response SendMail(string to, string subject, string body)
        {
            try
            {
                string from = _configuration["Mail:From"];
                string smtp = _configuration["Mail:Smtp"];
                string port = _configuration["Mail:Port"];
                string password = _configuration["Mail:Password"];

                MimeMessage message = new MimeMessage();
                message.From.Add(new MailboxAddress(from));
                message.To.Add(new MailboxAddress(to));
                message.Subject = subject;
                BodyBuilder bodyBuilder = new BodyBuilder
                {
                    HtmlBody = body
                };
                message.Body = bodyBuilder.ToMessageBody();

                using (SmtpClient client = new SmtpClient())
                {
                    client.CheckCertificateRevocation = false;
                    client.Connect(smtp, int.Parse(port), false);                   
                    client.Authenticate(from, password);
                    client.Send(message);
                    client.Disconnect(true);
                }

                return new Response { IsSuccess = true };

            }
            catch (Exception ex)
            {
                return new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                    Result = ex
                };
            }
        }

The error message is the following:

"534: 5.7.14 \u003Chttps://accounts.google.com/signin/continue?sarp=1\u0026scc=1\u0026plt=AKgnsbt\n5.7.14 GCim6bqtaJeANyyQ0NvegYJS8qnYbDSCz3M0IMvB-rgIFdr1rLrIl1wbt4DkimTvNMLDl\n5.7.14 8dSGZxGuAWmDwX6gPD1T_lJ3U1e0G8EEAu6Lgt3p5gk1yJpr85Pm2mBN9nO4G33Y\u003E\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 t15sm12262168pjy.17 - gsmtp"

Am I sending correctly? Should I change any gmail settings?

In the development environment the sending works without problems, any help or suggestion for me?

CodePudding user response:

Directly using providers like Gmail, Outlook and similar ones is not advised because they perform checks that can disrupt your code just like you're seeing here.

This can happen without previous notice. And believe me, it will happen from time to time.

Common issues

Web-based OAuth flow

Most providers (Gmail specially) now enforce a web-based flow, from the most recent OAuth/OpenID specifications, for safer authentication/authorization.

This would be my first guess: Gmail auth (which is browser based) is simply blocking your login attempt because it wants you to use a browser and not simply submit your credentials.

There's a lot of background work done by IAM solutions to help protect users, namely called risk assessment. This, in time, might require both captcha and MFA challenges to be sent back to the user, so an API would not really work on this, that's another reason why they focus on browsers and not simply on getting the correct credentials.

Bot prevention

Email providers (specially Gmail) are great at detecting possible bots and this would be my second guess: it detected your service as a bot and put a temporary hold on your account to "protect you".

It's possible that this works on lower environments (aka: your machine and/or testing environment) and not production because of the server bot prevention system, which typically inspects IP address, user agent from the browser (if any), API call rate, authentication rate and others.

Usage rate limit

Yet another thing that can block you when doing such integration is the rate limit. Typically, 500 messages/month.


Possible solutions

Workaround - still using Gmail

To workaround this and still use Gmail, this is the way to go: https://support.google.com/accounts/answer/185833?hl=en

It's called application password and is a different password that you generate on your account for a particular app to be allowed signing in. That will skip the OAuth and the bot validation (at least on most cases).

Proper long-term solution

The only reliable way to have this fixed is to use a proper send email service. Something like Amazon Simple Email Service, Sendgrid, or a bunch of others out there.

That's because they are created to be used by API calls and won't get in your way. You can set-up your own domain there, including SPF and DKIM keys so your recipient's email server will recognize the message as safe and indeed as coming from your (and not a random SPAM).

  •  Tags:  
  • Related