Flutter集成Firebase后,实现向当前用户发送邮件的问题求助
解决向当前Firebase用户邮箱发送邮件的问题
要实现向当前登录的Firebase用户邮箱发送邮件,只需从Firebase Auth中获取当前用户的邮箱地址,替换代码里的固定收件邮箱即可,具体步骤如下:
确认引入Firebase Auth依赖
若尚未导入firebase_auth包,先在pubspec.yaml中添加依赖并执行flutter pub get:dependencies: firebase_auth: ^latest_version修改sendMail函数
从FirebaseAuth实例中获取当前用户的邮箱,替换原固定收件地址,同时增加用户未登录的判断逻辑:
import 'package:firebase_auth/firebase_auth.dart'; // 导入mailer相关依赖 sendMail() async { // 获取当前Firebase登录用户实例 final currentUser = FirebaseAuth.instance.currentUser; // 检查用户是否已登录 if (currentUser == null) { print('用户未登录,无法获取目标邮箱'); return; } String username = 'example@gmail.com'; String password = 'axneqgkraxm'; final smtpServer = gmail(username, password); final message = Message() ..from = Address(username, 'testing') // 替换为当前用户的邮箱地址 ..recipients.add(currentUser.email!) ..subject = 'Receipt :: ${DateTime.now()}' ..text = 'This is the plain text.\nThis is line 2 of the text part.' ..html = html .replaceFirst('{{title}}', 'this will be the title') .replaceFirst('{{price}}', '20') .replaceFirst('{{hours}}', '2:00 PM') .replaceFirst('{{description}}', 'this is description'); try { final sendReport = await send(message, smtpServer); print('Message sent: ' + sendReport.toString()); } on MailerException catch (e) { print(e); print('Message not sent.'); for (var p in e.problems) { print('Problem: ${p.code}: ${p.msg}'); } } }
关键说明
FirebaseAuth.instance.currentUser会返回当前登录用户的实例,未登录时为null,必须先做非空判断避免运行时错误。currentUser.email!使用感叹号是因为已登录用户(非匿名)必然存在邮箱字段,若涉及匿名用户场景,需额外处理(比如提示用户绑定邮箱)。
内容的提问来源于stack exchange,提问作者noname
相关产品推荐
相关产品推荐

