Gmail PHP API Sending Email

徘徊边缘 提交于 2020-01-04 04:42:07

问题


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/myemailaddress@gmail.com/messages/send: (400) Invalid value for ByteString:

Any idea what is happening here? Thanks!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/25694923/gmail-php-api-sending-email

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!