如下面我的尝试所示,我正在尝试使用Laravel 5.2和oriceon/oauth-5-laravel package来授权我的网站上的用户,然后允许该用户通过我的网站向其他人发送电子邮件到他们自己的帐户。 / p>
Attempt:1 using laravels inbuilt swift_message(note emails are just examples)
$message = Swift_Message::newInstance();
$message->setSubject("Test Email");
$message->setFrom("dukeforsythtester@gmail.com");
$message->setTo("tester@gmail.com");
$message->setReplyTo("dukeforsythtester@gmail.com");
$message->setBody("This is a test of adding a body!");
$to_send = rtrim(strtr(base64_encode($message->toString()), '+/', '-_'),'=');
$result = $googleService->request('https://www.googleapis.com/gmail/v1/users/me/messages/send',$to_send);
Attempt 2: using imap_mail_compose via php natively
$envelope["from"]= "dukeforsythtester@gmail.com";
$envelope["to"] = "dukeforsyth@outlook.com";
$envelope["subject"] = "Testing...";
$part1["type"] = TYPETEXT;
$part1["subtype"] = "plain";
$part1["description"] = "description3";
$part1["contents.data"] = "contents.data3\n\n\n\t";
$body[1] = $part1;
$mime = imap_mail_compose ($envelope , $body);
$mime = rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');
$result = $googleService->request('https://www.googleapis.com/gmail/v1/users/me/messages/send',$mime);
无论哪种方式,我都有以下回复:
TokenResponseException in StreamClient.php line 68:
Failed to request resource. HTTP Code: HTTP/1.1 400 Bad Request
我相信我有正确的范围'https://www.googleapis.com/auth/gmail.send',用于在用户授权后为其发送电子邮件。我还确保来自发件人地址的是授权用户的电子邮件地址,但我不确定我是在做一些愚蠢的事情还是遗漏了编码中的内容。
任何帮助都会非常感激,现在已经坚持了两天!
答案 0 :(得分:2)
以下是使用Laravel 5.2和oriceon / oauth-5-laravel软件包以及google的google / apiclient软件包发送实际消息的解决方案。非常感谢@ Mr.Rebot的指导!
$code = Input::get('code');
$googleService = \OAuth::consumer('Google');
// if code is provided get user data and sign in
if ( ! is_null($code) )
{
// Variables
$redirect_uri = 'your redirect url that is set on google console';
$user_to_impersonate = 'dukeforsythtester@gmail.com';
// Create client with these set credentials
$client = new \Google_Client();
$client->setAuthConfig('path to your json given by google console');
$client->setRedirectUri($redirect_uri);
$client->setSubject($user_to_impersonate);
$scopes = [ \Google_Service_Gmail::GMAIL_SEND ];
$client->setScopes($scopes);
$token = $client->authenticate($code);
$client->setAccessToken($token);
if( $client->isAccessTokenExpired() )
{
// need to refresh token
$refreshToken = $client->refreshToken($token);
$client->setAccessToken($refreshToken);
}
// Create the service
$service = new \Google_Service_Gmail($client);
// Create the message
$msg = new \Google_Service_Gmail_Message();
$msg->setRaw($this->create_message());
// Send off the message
$this->sendMessage($service, 'me', $msg);
}
else {
// Get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to google login url
return redirect((string)$url);
}