send email using gmail-api and google-api-php-client

北慕城南 提交于 2019-12-01 12:47:04
Gavin Palmer

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 = "myemail@gmail.com";
$fname = "my name";
$mail->From = $from;
$mail->FromName = $fname;
$mail->AddAddress("tosomeone@somedomain.com");
$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);
Pim Van Vlaenderen

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);

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), '+/=', '-_,')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!