I'm New to flutter and dart mobile app development. how to implement forgot password and send verification mail in flutter/dart development or is there any way to implement to send mail.


Solution 1: Rainer Wittmann

I don't think there is any way to send an email from your flutter application. This is something I would definitely implement on a backend server.

I would implement a 'forgot password' button in flutter, which triggers a http call to the backend which then triggers the password generation and email sending.


Solution 2: Shimron Alakkal

Yes there are some ways. The most common would be to use firebase as a backend server handling these requests.

You could do it like this

Add these packages to your flutter apps pubspec.yaml file

// latest version
firebase_core: ^1.17.0
firebase_auth: ^3.3.18 

On forgot password button click

once you've completed the logic necessary before making the request, call this function

sendResetEmail(String email, BuildContext context) async {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  try {
    await _auth.sendPasswordResetEmail(email: email);
    Timer(
      const Duration(seconds: 3),
      () => CustomWidgets().moveToPage(
        page: const Home(), context: context, replacement: true),
  );
 } catch (e) {
  // error handling here
}

}

This will send an email from firebase to the selected email to reset password.

On email verification request

Once the logic is over, call this function.

bool _isEmailVerified = false;
Timer? timer;
final FirebaseAuth _auth = FirebaseAuth.instance;

the initstate method

@override
void initState() {
_isEmailVerified = _auth.currentUser!.emailVerified;

if (!_isEmailVerified) {
  sendEmailVerificationForUser();
  timer = Timer.periodic(const Duration(seconds: 5), (timer) {
    emailVerificationStatus(context);
  });
}

email verification check function

emailVerificationStatus(BuildContext context) async {
try {
  await _auth.currentUser!.reload();
  setState(() {
    _isEmailVerified = _auth.currentUser!.emailVerified;
  });
} catch (e) {
  // handle the error here 
}
setState(() {
  _isEmailVerified = _auth.currentUser!.emailVerified;
});

if (_isEmailVerified) {
  timer?.cancel();

// and move to next page

}}

send email verification function

Future sendEmailVerificationForUser() async {
try {
  await FirebaseAuth.instance.currentUser!.sendEmailVerification();
} catch (e) {
  // error handling}