send email using gmail-api and google-api-php-client



PHP Snippet 1:

require_once 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$subject = "my subject";
$msg = "hey there!";
$from = "[email protected]";
$fname = "my name";
$mail->From = $from;
$mail->FromName = $fname;
$mail->AddAddress("[email protected]");
$mail->AddReplyTo($from,$fname);
$mail->Subject = $subject;
$mail->Body    = $msg;
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service->users_messages->send('me', $m);

PHP Snippet 2:

$mail->Encoding = 'base64';

PHP Snippet 3:

//prepare the mail with PHPMailer
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->Encoding = "base64";

//supply with your header info, body etc...
$mail->Subject = "You've got mail!";
...

//create the MIME Message
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$mime = rtrim(strtr(base64_encode($mime), '+/', '-_'), '=');

//create the Gmail Message
$message = new Google_Service_Gmail_Message();
$message->setRaw($mime);
$message = $service->users_messages->send('me',$message);

PHP Snippet 4:

// This block is only needed if you're working outside the global namespace
use \Google_Client as Google_Client;
use \Google_Service_Gmail as Google_Service_Gmail;
use \Google_Service_Gmail_Message as Google_Service_Gmail_Message;

// Prep things for PHPMailer
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

// Grab the needed files
require_once 'path/to/google-api/vendor/autoload.php';
require_once 'path/to/php-mailer/Exception.php';
require_once 'path/to/php-mailer/PHPMailer.php';

// Replace this with your own data
$pathToServiceAccountCredentialsJSON = "/path/to/service/account/credentials.json";
$emailUser = "[email protected]"; // the user who is "sending" the email...
$emailUserName = "Sending User's Name"; // ... and their name
$emailSubjectLine = "My Email's Subject Line";
$recipientEmail = "[email protected]";
$recipientName = "Recipient's Name";
$bodyHTML = "<p>Paragraph one.</p><p>Paragraph two!</p>";
$bodyText = "Paragraph one.\n\nParagraph two!";

// Set up credentials and client
putenv("GOOGLE_APPLICATION_CREDENTIALS={$pathToServiceAccountCredentialsJSON}");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
// We're only sending, so this works fine
$client->addScope(Google_Service_Gmail::GMAIL_SEND);
// Set the user we're going to pretend to be (Subject is confusing here as an email also has a "Subject"
$client->setSubject($emailUser);

// Set up the service
$mailService = new Google_Service_Gmail($client);

// We'll use PHPMailer to build the raw email (since Google's API doesn't do that) so prep it
$mailBuilder = new PHPMailer();
$mailBuilder->CharSet = "UTF-8";
$mailBuilder->Encoding = "base64";

// Not set up the email you want to send
$mailBuilder->Subject = $emailSubjectLine;
$mailBuilder->From = $emailUser;
$mailBuilder->FromName = $emailUserName;
try {
    $mailBuilder->addAddress($recipientEmail, $recipientName);
} catch (Exception $e) {
    // Handle any problems adding the email address here
}
// Add additional recipients, CC, BCC, ReplyTo, if desired

// Then add the main body of the email...
$mailBuilder->isHTML(true);
$mailBuilder->Body = $bodyHTML;
$mailBuilder->AltBody = $bodyText;

// Prep things so we have a nice, raw message ready to send via Google's API
try {
    $mailBuilder->preSend();
    $rawMessage = base64_encode($mailBuilder->getSentMIMEMessage());
    $rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage); // url safe
    $gMessage = new Google_Service_Gmail_Message();
    $gMessage->setRaw($rawMessage);
    // Send it!
    $result = $mailService->users_messages->send('me', $gMessage);
} catch (Exception $e) {
    // Handle any problems building or sending the email here
}

if ($result->labelIds[0] == "SENT") echo "Message sent!";
else echo "Something went wrong...";

PHP Snippet 5:

Invalid value for ByteString

PHP Snippet 6:

$mail->Encoding = 'base64';

PHP Snippet 7:

strtr(base64_encode($val), '+/=', '-_*')

PHP Snippet 8:

strtr(base64_encode($val), '+/=', '-_,')