Google-api-php-client: Example of Gmail message with To/Bcc/CC recipients

Created on 11 Apr 2018  路  2Comments  路  Source: googleapis/google-api-php-client

Been banging my head against the wall trying to figure out how to compose a draft to a recipient, cc and bcc address, and then send it.

Would really appreciate an example of this.
I have no problem with authentication; just can't find an example of actually sending an email successfully :(

question

Most helpful comment

Thanks for the link @mattwhisenhunt
Yes I'm using the scopes properly; what I missed was how to generate the actual "message".

For anyone else in this position in the future, you need to generate a valid message body (likely using a 3rd party library). This includes things like the recipient, the body, the subject, bcc, cc, attachments, etc.

I'm using Swift Mailer to do this.
Here's an example:

$swiftMessage = new Swift_Message('Wonderful Subject');
$swiftMessage->setTo(['[email protected]']);
$swiftMessage->setBody('Here is the message itself');
$validMessageBody = $swiftMessage->toString();

You then set this in the Google_Service_Gmail_Message object you've created, like so:

$message = new Google_Service_Gmail_Message();
$body = strtr(
    base64_encode($validMessageBody),
    array('+' => '-', '/' => '_')
);
$message->setRaw($body);

That's what you want to set, and then send.
Gosh I hit my head against the wall for ages trying to figure out this one lololol

All 2 comments

https://developers.google.com/gmail/api/v1/reference/users/messages/send#examples

Are you using all four scopes?

define('SCOPES', implode(' ', array(
  Google_Service_Gmail::MAIL_GOOGLE_COM,
  Google_Service_Gmail::GMAIL_MODIFY,
  Google_Service_Gmail::GMAIL_COMPOSE,
  Google_Service_Gmail::GMAIL_SEND)
));

Thanks for the link @mattwhisenhunt
Yes I'm using the scopes properly; what I missed was how to generate the actual "message".

For anyone else in this position in the future, you need to generate a valid message body (likely using a 3rd party library). This includes things like the recipient, the body, the subject, bcc, cc, attachments, etc.

I'm using Swift Mailer to do this.
Here's an example:

$swiftMessage = new Swift_Message('Wonderful Subject');
$swiftMessage->setTo(['[email protected]']);
$swiftMessage->setBody('Here is the message itself');
$validMessageBody = $swiftMessage->toString();

You then set this in the Google_Service_Gmail_Message object you've created, like so:

$message = new Google_Service_Gmail_Message();
$body = strtr(
    base64_encode($validMessageBody),
    array('+' => '-', '/' => '_')
);
$message->setRaw($body);

That's what you want to set, and then send.
Gosh I hit my head against the wall for ages trying to figure out this one lololol

Was this page helpful?
0 / 5 - 0 ratings