【发布时间】: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