kaisellgren / mailer

Compose and send emails from Dart. Supports file attachments, HTML emails and multiple transport methods.
MIT License
168 stars 88 forks source link

Unhandled Exception: Incorrect username / password / credentials #127

Open bhanuka96 opened 4 years ago

bhanuka96 commented 4 years ago

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('sample@gmail.com')
            ..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();
close2 commented 4 years ago

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

kashifg4171 commented 4 years ago

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

close2 commented 4 years ago

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

joshiprashanthd commented 3 years ago

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("example@gmail.com")
      ..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?

close2 commented 3 years ago

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 commented 3 years ago

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.

joshiprashanthd commented 3 years ago

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

close2 commented 3 years ago

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 .

soaresmp commented 3 years ago

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

close2 commented 3 years ago

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.

alexobviously commented 3 years ago

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 = 'mailer@my-gcloud-project.iam.gserviceaccount.com';
  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('myemail@gmail.com')
    ..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.

close2 commented 3 years ago

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.

abelokon0711 commented 2 years ago

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

vanlooverenkoen commented 2 years ago

Anyone who has found a fix for this?

mohitmarfatia-aibender commented 1 year ago

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

close2 commented 1 year ago

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