scope(['https://mail.google.com/']); it will working proper but google suggest use scopes: ['email', 'https://www.googleapis.com/auth/gmail.send']);
To use the Gmail API and continue with the verification process, you need to migrate off SMTP protocol. Instead you should use the https://www.googleapis.com/auth/gmail.send scope. This scope still gives your project enough access to work properly.
If your app uses SMTP protocol only, note that using the broad access https://mail.google.com/ scope just for sending emails with the SMTP protocol violates the minimum scope policy. To use the Gmail API and continue with the verification process, you will need to migrate off SMTP protocol and use the sensitive https://www.googleapis.com/auth/gmail.send scope instead.
pubspec.yaml
dependencies:
mailer: ^6.0.0
firebase_core: ^2.9.0
firebase_auth: ^4.4.0
google_sign_in: ^5.0.0
sendMail()
Future<void> sendEmail() async {
SmtpServer? smtpServer;
try {
// Setting up Google SignIn
final googleSignIn = GoogleSignIn.standard(
scopes: ['email', 'https://www.googleapis.com/auth/gmail.send']);
// Signing in
final account = await googleSignIn.signIn();
if (account == null) {
// User didn't authorize
return;
}
final auth = await account.authentication;
// Creating SMTP server from the access token
smtpServer = gmailSaslXoauth2(account.email,auth.accessToken!);
} on PlatformException catch (e) {
print(e);
}
final message = Message()
..from = Address('[email protected]', 'Your name')
..recipients.add('[email protected]')
..subject = 'Test Dart Mailer library'
..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>";
// Ready to send a message now
final sendReport = await send(message, smtpServer!);
}
Unhandled Exception: Authentication Failed (code: 334)
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Authentication Failed (code: 334), response:
< eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
#0 _doAuthentication (package:mailer/src/smtp/smtp_client.dart:106:5)
<asynchronous suspension>
#1 connect (package:mailer/src/smtp/smtp_client.dart:136:5)
<asynchronous suspension>
#2 send (package:mailer/src/smtp/mail_sender.dart:93:20)
<asynchronous suspension>
#3 _MyHomePageState.sendEmail (package:send_mail/main.dart:102:24)
<asynchronous suspension>