Бортовой журнал Ктулху

Отправка почты с вложением методом Gmail API message.send на PHP и curl | Gmail API message.send using PHP and curl with attachments

Сегодня будет отправка почты с вложением методом Gmail API message.send на PHP и curl.

$access_token = "YOUR_ACCESS_TOKEN_HERE";
$api_endpoint = "https://www.googleapis.com/gmail/v1/users/me/messages/send";
// Create message data
$message_data = array(
"raw" => base64_encode("From: sender[pes]example.com\r\n"
. "To: recipient[pes]example.com\r\n"
. "Subject: EMAIL_SUBJECT\r\n"
. "MIME-Version: 1.0\r\n"
. "Content-Type: multipart/mixed; boundary=boundary_text\r\n\r\n"
. "--boundary_text\r\n"
. "Content-Type: text/plain; charset=UTF-8\r\n\r\n"
. "EMAIL_BODY\r\n\r\n"
. "--boundary_text\r\n"
. "Content-Type: APPLICATION_CONTENT_TYPE; name=41094_5MiB.pdf\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "Content-Disposition: attachment; filename=41094_5MiB.pdf\r\n\r\n"
. base64_encode(file_get_contents($attachmentPath)) . "\r\n"
. "--boundary_text--\r\n")
);
// Set cURL options
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $api_endpoint);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_PROXY, PROXY);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer " . $accessToken,
"Content-Type: application/json"
));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($message_data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute cURL request
$response = curl_exec($curl);
curl_close($curl);
// Output response
echo $response;

Результат:

2023 03 30 14.14.45