2

I want to send an email using a particular email address. But in my app first I sign in using google and then send emails using Gmail API using logged in user auth-headers.

But in this, anyone can log in and send emails. but I want only a particular email can send emails from my app. So I statically store auth headers for that particular email and sending email but my problem is that auth headers is expire after some time.

Here my code for google sign In:

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);
    });
});

Code for send email:

  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");
    }
  }

Help me to sort out this problem

Darshan Prajapati
  • 914
  • 3
  • 8
  • 19
  • Once you have your token you can just store and load it. Use offline_access when authenticating to allow it to be refreshed without prompting from the user. More information about it [here](https://stackoverflow.com/a/60815451/11551468). – Rafa Guillermo Aug 12 '20 at 11:22

1 Answers1

0

You can refresh your token

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;
}
Johny Saini
  • 879
  • 1
  • 5
  • 6
  • How can I statically store _auth for a particular email in code? Because this _auth is getting after google sign in but I don't want to do that because anyone can log in using a different email and then send emails. – Darshan Prajapati Aug 12 '20 at 10:16