mailer icon indicating copy to clipboard operation
mailer copied to clipboard

Unhandled Exception: Incorrect username / password / credentials

Open bhanuka96 opened this issue 6 years ago • 16 comments

My Username and password are correct. And also I enable Access to less secure app feature on gmail. How to fix this issue?

          final smtpServer = gmail(username, password);

          final message = Message()
            ..from = Address(username, 'Yello')
            ..recipients.add('[email protected]')
            ..subject = 'Test Dart Mailer library :: 😀 :: ${DateTime.now()}'
            ..text = 'This is the plain text.\nThis is line 2 of the text part.'
            ..html = "<h1>Test</h1>\n<p>Hey! Here's some HTML content</p>";

          try {
            final sendReport = await send(message, smtpServer);
            print('Message sent: ' + sendReport.toString());
          } on MailerException catch (e) {
            print('$e');
            for (var p in e.problems) {
              print('Problem: ${p.code}: ${p.msg}');
            }
          }
          var connection = PersistentConnection(smtpServer);
          await connection.close();

bhanuka96 avatar Dec 28 '19 16:12 bhanuka96

Can you please try if the same credentials work in another mailing app.

In any case I would recommend using: https://github.com/kaisellgren/mailer/tree/master/example/gmail_xoauth2

close2 avatar Dec 30 '19 09:12 close2

This exception will be handled from gmail account's security setting, Where you have to enable Less secure App Access. Capture

kashifg4171 avatar Jan 24 '20 14:01 kashifg4171

I'll try to improve the documentation. Feel free to send a PR.

close2 avatar Jun 26 '20 16:06 close2

I am using Google APIs and created a service account. I copied service account content into a Map<String, String> variables named CLIENT_JSON. I've done everything, written in googleapis_auth pub readme. But still getting this error.

Future<AccessCredentials> getAccessToken() async {
    var accountCredentials = ServiceAccountCredentials.fromJson({
      "private_key_id": CLIENT_JSON["private_key_id"],
      "private_key": CLIENT_JSON["private_key"],
      "client_email": CLIENT_JSON["client_email"],
      "client_id": CLIENT_JSON['client_id'],
      "type": "service_account"
    });

    AccessCredentials accessCredentials;
    final client = http.Client();

    try {
      accessCredentials = await obtainAccessCredentialsViaServiceAccount(
          accountCredentials, ["https://mail.google.com/"], client);
      print("[EMAIL_SERVICE] Access Token Fetched");
    } on Exception catch (err) {
      print("[EMAIL_SERVICE] Error in fetching access token. Error: $err");
    }

    client.close();
    return accessCredentials;
  }

  Future<void> sendEmailFromConfibuddy({
    @required String receiverEmail,
    @required String subject,
    @required String body,
  }) async {
    final credentials = await getAccessToken();

    if (credentials == null) {
      print("[EMAIL_SERVICE] Credentials are null.");
      return;
    }

    final smtpServer = gmailSaslXoauth2(
        CLIENT_JSON["client_email"], credentials.accessToken.data);

    final message = Message()
      ..from = Address(CLIENT_JSON["client_email"], 'Confibuddy')
      ..recipients.add("[email protected]")
      ..subject = subject
      ..html = body;

    try {
      final sendReport = await send(message, smtpServer);
      print('Message sent: ' + sendReport.toString());
    } on MailerException catch (e) {
      print('Message not sent.');
      for (var p in e.problems) {
        print('Problem: ${p.code}: ${p.msg}');
      }
    }
  }
}

Right now, the access token is generating successfully but I am not sure, about using client_email field. Should I use my personal gmail account in which I created Service Accounts?

joshiprashanthd avatar Mar 12 '21 15:03 joshiprashanthd

I don't see any obvious mistakes in your code.

Please enable debug log output:

    Logger.root.level = Level.ALL;
    Logger.root.onRecord.listen((LogRecord rec) {
      print('${rec.level.name}: ${rec.time}: ${rec.message}');
    });

This will hopefully give a better error message (the response from google)

close2 avatar Mar 13 '21 20:03 close2

I've deleted your comment as it included your mail address and oauth token.

That looks good. 334 => authentication accepted. Is this the last line of your debug output? The next line after the 334 response code should indicate if google accepted your oauth token or not. Usually with additional information.

close2 avatar Mar 16 '21 20:03 close2

Thanks, man, I totally forgot about the email and token. And no, I am not getting any message indicating acceptance of my OAuth. I next message I am getting is Message not sent which is from try..catch block.

Is there any way, this could be related to the permissions or roles defined in my developer console. Service account permissions defined like this console

joshiprashanthd avatar Mar 17 '21 14:03 joshiprashanthd

Could you please try version 5

It fixed a lot of bugs and probably also yours.

Regards Christian

On Wed, 17 Mar 2021, 15:42 Prashant Joshi, @.***> wrote:

Thanks, man, I totally forgot about the email and token. And no, I am not getting any message indicating acceptance of my OAuth. I next message I am getting is Message not sent which is from try..catch block.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/kaisellgren/mailer/issues/127#issuecomment-801140316, or unsubscribe https://github.com/notifications/unsubscribe-auth/AACZDOJRK7VYMSDMNL656VDTEC5ULANCNFSM4KAPEBQQ .

close2 avatar Mar 31 '21 15:03 close2

I am facing the the same issue ... looks like the token is generated and valid, but credentials fails when sending

soaresmp avatar Apr 13 '21 14:04 soaresmp

Please enable debug output:

    Logger.root.level = Level.ALL;
    Logger.root.onRecord.listen((LogRecord rec) {
      print('${rec.level.name}: ${rec.time}: ${rec.message}');
    });

Hide your token and post the output.

close2 avatar May 23 '21 10:05 close2

Hey, I'm getting this error too @close2

My code:

main(List<String> rawArgs) async {
  Logger.root.level = Level.ALL;
  Logger.root.onRecord.listen((LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });
  String username = '[email protected]';
  Map<String, String> env = Platform.environment;
  ServiceAccountCredentials serviceAccCreds = ServiceAccountCredentials.fromJson(env['AAC_GS']);
  final client = http.Client();
  AccessCredentials credentials = await obtainAccessCredentialsViaServiceAccount(serviceAccCreds, scopes, client);
  client.close();
  final oauth2token = base64Encode(
      utf8.encode('user=$username\x01auth=${credentials.accessToken.type} ${credentials.accessToken.data}\x01\x01'));
  // I also tried (username, credentials.accessToken.data) here like the guy above, same error
  final smtp = gmailSaslXoauth2(username, oauth2token);
  final message = Message()
    ..from = Address(username, 'Service acct')
    ..recipients.add('[email protected]')
    ..subject = 'this better work'
    ..text = 'asdf';

  try {
    final sendReport = await send(message, smtp);
    print('Message sent: ' + sendReport.toString());
  } on MailerException catch (e) {
    print('Message not sent. $e');
    for (var p in e.problems) {
      print('Problem: ${p.code}: ${p.msg}');
    }
  }
}

My logs:

FINER: 2021-08-13 13:03:59.133725: Connecting to smtp.gmail.com at port 465.
FINE: 2021-08-13 13:03:59.269937: > 
FINE: 2021-08-13 13:03:59.541400: < 220 smtp.gmail.com ESMTP gz23sm667488pjb.0 - gsmtp
FINE: 2021-08-13 13:03:59.546862: > EHLO Alexs-MacBook-Air.local
FINE: 2021-08-13 13:03:59.768370: < 250 smtp.gmail.com at your service, [156.146.57.199]
< 250 SIZE 35882577
< 250 8BITMIME
< 250 AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
< 250 ENHANCEDSTATUSCODES
< 250 PIPELINING
< 250 CHUNKING
< 250 SMTPUTF8
FINE: 2021-08-13 13:03:59.782192: > AUTH XOAUTH2 {very_long_token}
FINE: 2021-08-13 13:04:00.000132: < 555 5.5.2 Syntax error, goodbye. gz23sm667488pjb.0 - gsmtp
Message not sent. Incorrect username / password / credentials

btw my accessToken.data seems to have this very long string of 'Li4uLi4uLi4uLi4u' in it (maybe 100x) - is this normal?

If there's anything else you need from me, let me know.

alexobviously avatar Aug 13 '21 06:08 alexobviously

I can't easily reproduce your problem. Could you please verify that your token is correct. It seems really odd to me, that you have those Li4u characters.

The googleapis_auth library and XOAuth2 is not really my speciality.

close2 avatar Aug 15 '21 11:08 close2

alexobviously I'm having the same issue. Did you manage to resolve it?

abelokon0711 avatar Mar 16 '22 18:03 abelokon0711

Anyone who has found a fix for this?

vanlooverenkoen avatar Sep 09 '22 23:09 vanlooverenkoen

@abelokon0711 @vanlooverenkoen this guy got the same issue at 09:35 link See if it helps...

mohitmarfatia-aibender avatar Nov 30 '22 07:11 mohitmarfatia-aibender

Another workaround is to first enable 2-factor authentication and then create an app password.

close2 avatar Dec 02 '22 12:12 close2