You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter集成Firebase后,实现向当前用户发送邮件的问题求助

解决向当前Firebase用户邮箱发送邮件的问题

要实现向当前登录的Firebase用户邮箱发送邮件,只需从Firebase Auth中获取当前用户的邮箱地址,替换代码里的固定收件邮箱即可,具体步骤如下:

  1. 确认引入Firebase Auth依赖
    若尚未导入firebase_auth包,先在pubspec.yaml中添加依赖并执行flutter pub get:

    dependencies:
      firebase_auth: ^latest_version
    
  2. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:50:27