在我的网络应用程序中,用户可以使用他们的Gmail帐户登录该网站[我通过Oauth实现了这一点]。现在我想使用登录用户的Gmail帐户从我的应用程序向其他用户发送电子邮件。怎么可以这样做?
我的简单index.php
<?php
session_start();
require_once 'google-api-php-client-master/src/Google/Client.php';
require_once 'google-api-php-client-master/src/Google/Service/Gmail.php';
// Replace this with you/r Google Client ID
$client_id = 'client id';
$client_secret = 'client secret';
$redirect_uri = 'https://localhost/mail/index.php'; // Change this
$server_key='server key';
$client = new Google_Client();
$client->setApplicationName("Mail sending application");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($server_key);
// We only need permissions to compose and send emails
$client->addScope("https://www.googleapis.com/auth/gmail.compose");
$service = new Google_Service_Gmail($client);
// Redirect the URL after OAuth
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// If Access Toket is not set, show the OAuth URL
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
if ($client->getAccessToken() && isset($_POST['message'])) {
$_SESSION['access_token'] = $client->getAccessToken();
// Prepare the message in message/rfc822
try {
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($_POST["message"]), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$service->users_messages->send("me", $msg);
} catch (Exception $e) {
print($e->getMessage());
unset($_SESSION['access_token']);
}
} ?>
<?php if ( isset ( $authUrl ) ) { ?>
<a href="<?php echo $authUrl; ?>">sign in</a>
<?php } else { ?>
<form method="POST" action="">
<textarea name="message" required></textarea>
<input type="email" required name="to">
<input type="text" required name="subject">
<a href="#" onclick="document.forms.htmlmail.submit();return false;">Send Mail</a>
</form>
<?php } ?>
它将我重定向到gmail页面,但之后它显示我这样的错误而不是邮件形式:
那是一个错误。
Error: invalid_client
no support email
Request Details
from_login=1
response_type=code
scope=https://www.googleapis.com/auth/gmail.compose
redirect_uri=https://localhost/mail/index.php
access_type=online
approval_prompt=auto
as=-4de25f3b2be1f07c
client_id=570442960066-01d3mblkltjfjjt9ivnqiki5vvanlas9.apps.googleusercontent.com
hl=en
答案 0 :(得分:1)
从Google查看gmail api。这是发送时的guides ..
还有php client library可用,处于测试阶段。
检查此blog post代码示例。 检查关于该主题的stackoverflow讨论。