【问题标题】:I have to send emails using particular gmail account in flutter我必须在颤动中使用特定的 gmail 帐户发送电子邮件
【发布时间】:2023-04-01 01:27:02
【问题描述】:

我想使用特定的电子邮件地址发送电子邮件。但在我的应用程序中,我首先使用 google 登录,然后使用登录用户 auth-headers 使用 Gmail API 发送电子邮件。

但在此,任何人都可以登录并发送电子邮件。但我希望只有一个特定的电子邮件可以从我的应用程序发送电子邮件。因此,我静态存储该特定电子邮件和发送电子邮件的身份验证标头,但我的问题是身份验证标头在一段时间后过期。

这是我的谷歌登录代码:

GoogleSignIn googleSignIn = new GoogleSignIn(
  scopes: <String>['https://www.googleapis.com/auth/gmail.send'],
);

await googleSignIn.signIn().then((data) async {
    await data.authHeaders.then((result) async {
      var header = {
        'Authorization': result['Authorization'],
        'X-Goog-AuthUser': result['X-Goog-AuthUser']
      };
      await testingEmail(data.email, header);
    });
});

发送邮件代码:

  Future<Null> testingEmail(String userId, Map header) async {
    header['Content-type'] = 'application/json';

    var from = userId;
    var to = 'email in which send email';
    var subject = 'subject of mail';
    var message = 'Body of email';
    var content = '''
      Content-Type: text/plain; charset="us-ascii"
      MIME-Version: 1.0
      Content-Transfer-Encoding: 7bit
      to: $to
      from: 'Email alias name <$from>'
      subject: $subject
      $message''';

    var bytes = utf8.encode(content);
    var base64 = base64Encode(bytes);
    var body = json.encode({'raw': base64});

    String url = 'https://www.googleapis.com/gmail/v1/users/' +
        userId +
        '/messages/send';

    final http.Response response =
        await http.post(url, headers: header, body: body);
    if (response.statusCode != 200) {
      return Future.error("Something went wrong");
    }
  }

帮我解决这个问题

【问题讨论】:

  • 获得令牌后,您可以存储和加载它。在进行身份验证时使用 offline_access 以允许在不提示用户的情况下对其进行刷新。有关它的更多信息here

标签: flutter email google-api gmail-api google-signin


【解决方案1】:

你可以刷新你的令牌

Future<String>  getRefreshToken()async{
if(_auth?.currentUser() !=null){
  //   print("user----------${_auth.currentUser()}");
 FirebaseUser user =   await _auth?.currentUser();
 if(user !=null){
dynamic value = await  user?.getIdToken(refresh: true);
 String tokenValue = value?.token;   
  return tokenValue; 
}
return null;
} 
 return null;
}

【讨论】:

  • 如何在代码中静态存储特定电子邮件的 _auth?因为这个 _auth 是在谷歌登录之后得到的,但我不想这样做,因为任何人都可以使用不同的电子邮件登录,然后发送电子邮件。
猜你喜欢
  • 1970-01-01
  • 2012-03-30
  • 2016-04-20
  • 1970-01-01
  • 2019-02-04
  • 2011-04-06
  • 2011-12-15
  • 2013-03-24
  • 2016-10-31
相关资源
最近更新 更多