Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gmail PHP API Sending Email

Tags:

php

gmail-api

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!

like image 569
ewein Avatar asked Oct 15 '25 08:10

ewein


1 Answers

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.

like image 118
Alexander Kleinhans Avatar answered Oct 17 '25 10:10

Alexander Kleinhans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!