Bounce & lt; nobody@gmail.com> Ошибка отправки API Gmail

Я пытаюсь отправлять электронные письма с помощью Google API. Я могу читать электронные письма, аутентифицироваться с помощью присяги, используя client_secret.json файл в соответствии с быстрый старт инструкции. Я почти получил отправку электронной почты, но не могу отправить успешно.

Мое электронное письмо отскочило, и я не могу указать электронное письмо, которое я отправляю (следовательно, nobody@gmail.com адрес).

Код здесь ниже работает по большей части. Я закомментировал части, которые работают: (чтение электронных писем).

Код:

<?php
require 'google-api-php-client/src/Google/autoload.php';

define('APPLICATION_NAME', 'Gmail API Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-api-quickstart.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Gmail::MAIL_GOOGLE_COM,
Google_Service_Gmail::GMAIL_COMPOSE)
));

/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setAccessType('offline');

// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));

// Exchange authorization code for an access token.
$accessToken = $client->authenticate($authCode);

// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, $accessToken);
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, $client->getAccessToken());
}
return $client;
}

/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
}
return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);


$msg = new Google_Service_Gmail_Message();
$mime = rtrim(strtr(base64_encode("TEST MESSAGE OR SOMETHING"), '+/', '-_'), '=');
$msg->setRaw($mime);

// Print the labels in the user's account.
$userId = 'me';

function sendMessage($service, $userId, $message) {
try {
$message = $service->users_messages->send($userId, $message);
print 'Message with ID: ' . $message->getId() . ' sent.';
// <----------- GET'S HERE AND THIS WORKS
return $message;
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
}

try {
sendMessage($service, $userId, $msg);
} catch (Exception $Ex ) {
echo $Ex->getMessage();
}

Ответ по электронной почте (В моем почтовом ящике Gmail):

An error occurred. Your message was not sent.

TEST MESSAGE OR SOMETHING Date: Tue, 21 Jul 2015 14:51:12 -0700 Message-Id: <

Я не уверен, как даже указать адрес назначения, как personimsendingto@gmail.com, Я не мог найти много на пути к документации. Если бы кто-то мог помочь мне или указать мне правильное направление, я был бы очень благодарен.

1

Решение

Вам нужно поместить все сообщение электронной почты RFC822 в необработанное поле. Так что, где у вас есть «ТЕСТОВОЕ СООБЩЕНИЕ ИЛИ ЧТО-ТО», вы должны иметь такую ​​строку:

To: someguy@gmail.com
From: myaddress@gmail.com
Subject: this is my cool subject

here's a text/plain email, neato?

не забудьте иметь \r\n между строками и двумя между заголовками и телом. кажется, что для php PEAR :: Mail_Mime хорошая библиотека для создания таких строк сообщений электронной почты MIME rfc822.

Для получения дополнительной информации см. Отправка электронной почты.

2

Другие решения

Других решений пока нет …