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

后端 未结 5 1358
感动是毒
感动是毒 2021-01-16 03:24

I am using https://github.com/google/google-api-php-client and I want to send a test email with a user\'s authorized gmail account.

This is what I have so far:

5条回答
  •  隐瞒了意图╮
    2021-01-16 04:18

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

提交回复
热议问题