3
votes

I am trying to send an email through the Gmail PHP API (https://developers.google.com/gmail/api/v1/reference/users/messages/send). Everything seems to work up to the point that I send the message. My code is:

private function createMessage($email) {
    $message = new Google_Service_Gmail_Message();
     $message->setRaw(strtr(base64_encode($email), '+/=', '-_,'));      // $email is a raw email data string
    return $message;
}

public function sendMessage($userID, $email) {
    try {
        $msg = $this->createMessage($email);
        $this->service->users_messages->send($userID, $msg);
    } catch (Exception $e) {
        print 'An error occurred: ' . $e->getMessage();
    }
}

The code is breaking at the line:

$this->service->users_messages->send($userID, $msg);

with the error:

An error occurred: Error calling POST https://www.googleapis.com/gmail/v1/users/[email protected]/messages/send: (400) Invalid value for ByteString:

Any idea what is happening here? Thanks!

2
can you please provide example with full raw message you sending? I have difficulty to send emails.Ing. Michal Hudak

2 Answers

4
votes

The email string you set to 'raw' needs to be url safe base64 encoded (slightly different alphabet).

5
votes

The problem, like Eric said, is the url safe base 64. You need to change the url conversion to something more like this:

$message_object = new Google_Service_Gmail_Message();
$encoded_message = rtrim(strtr(base64_encode("PUT MESSAGE HERE"), '+/', '-_'), '=');
$message_object->setRaw($encoded_message);

Also make sure to use a valid mail mime, so "PUT MESSAGE HERE" would not work in reality. You'll need to include valid headers like subject, etc. There are some various PHP libraries to make these, or if you can make it yourself in plain text.