'send email using gmail-api and google-api-php-client
I am using https://github.com/google/google-api-php-client and I want to send a test email with a user's authorized gmail account.
This is what I have so far:
$msg = new Google_Service_Gmail_Message();
$msg->setRaw('gp1');
$service->users_messages->send('me', $msg);
This results in a bounce email because I have no clue how to set the raw message. I see the bounce in the inbox of my authenticated user. I want to learn how to set values for 'To', 'Cc', 'Bcc', 'Subject', and 'Body' of the email. I believe I will need to do a 64 encoding on that raw data as well. And I might want to use some html in the body of my email.
Please help to provide a working example of sending an email using the gmail-api and the google-api-php-client.
Here is the bounced email in the inbox:
Bounce [email protected] 12:58 PM (7 minutes ago)
to me
An error occurred. Your message was not sent.‚ Date: Thu, 24 Jul 2014 10:58:30 -0700 Message-Id: CABbXiyXhRBzzuaY82i9iODEiwxEJWO1=jCcDM_TH-
Solution 1:[1]
I asked a more specific question which has led me to an answer. I am now using PHPMailer to build the message. I then extract the raw message from the PHPMailer object. Example:
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);
Solution 2:[2]
I've used this solution as well, worked fine with a few tweaks:
When creating the PHPMailer object, the default encoding is set to '8bit'. So I had to overrule that with:
$mail->Encoding = 'base64';
The other thing i had to do was tweaking the MIME a little to make it POST ready for the Google API, I've used the solution by ewein:
Invalid value for ByteString error when calling gmail send API with base64 encoded < or >
Anyway, this is how I've solved your problem:
//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);
Solution 3:[3]
Perhaps this is a bit beyond the original question, but at least in my case that "test email" progressed to regularly sending automated welcome emails "from" various accounts. Though I've found much that is helpful here, I've had to cobble things together from various sources.
In the hope of helping others navigate this process, here's a distilled version of what I came up with.
A few notes on the following code:
- This assumes that you've jumped through the hoops to create and download the JSON for a Google Service Account (under credentials in the developer dashboard it's the bottom section.)
- For clarity, I've grouped all the bits you should need to set in the "Replace this with your own data" section.
- That
me
in thesend()
method is a key word that means something like "send this email with the current account."
// 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...";
Solution 4:[4]
Create the mail with phpmailer works fine for me in a local enviroment. On production I get this error:
Invalid value for ByteString
To solve this, remove the line:
$mail->Encoding = 'base64';
because the mail is two times encoded.
Also, on other questions/issues I found the next:
use
strtr(base64_encode($val), '+/=', '-_*')
instead of
strtr(base64_encode($val), '+/=', '-_,')
Solution 5:[5]
I Used https://developers.google.com/gmail/api/v1/reference/users/messages/send
and able to send email successfully.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Community |
Solution 3 | |
Solution 4 | Jordi Touza Bonnin |
Solution 5 | Pravin Pagare |