How do I send email using gmail api php

倾然丶 夕夏残阳落幕 提交于 2019-12-18 18:26:14

问题


How do I send email using gmail api php

$msg['raw'] = "This is sample test message";            
$msg['To'] = "test.api@gmail.com";
$msg['subject'] = "Sample test subject";

currently i am using $message = $service->users_messages->send('me', $msg);

Where to difine to,subject ?


回答1:


Based on http://www.pipiscrew.com/2015/04/php-send-mail-through-gmail-api/ here is the answer:

$user = 'me';
$strSubject = 'Test mail using GMail API' . date('M d, Y h:i:s A');
$strRawMessage = "From: myAddress<myemail@gmail.com>\r\n";
$strRawMessage .= "To: toAddress <recptAddress@gmail.com>\r\n";
$strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= "MIME-Version: 1.0\r\n";
$strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= "this <b>is a test message!\r\n";
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
//The special value **me** can be used to indicate the authenticated user.
$service->users_messages->send("me", $msg);



回答2:


Swiftmailer has all the tools for building base64 message.

Here is a full sample for sending a email:

// Visit https://developers.google.com/gmail/api/quickstart/php
// for an example of how to build the getClient() function.
$client = getClient();

$service = new \Google_Service_Gmail($client);
$mailer = $service->users_messages;

$message = (new \Swift_Message('Here is my subject'))
    ->setFrom('myemailaddress@myserver.com')
    ->setTo(['receiver@someserver.com' => 'Test Name'])
    ->setContentType('text/html')
    ->setCharset('utf-8')
    ->setBody('<h4>Here is my body</h4>');

$msg_base64 = (new \Swift_Mime_ContentEncoder_Base64ContentEncoder())
    ->encodeString($message->toString());

$message = new \Google_Service_Gmail_Message();
$message->setRaw($msg_base64);
$message = $mailer->send('me', $message);
print_r($message);



回答3:


I am using the same code and it does work fine except that it always sends a plain text email.

Isn't specifying Content-Type: text/html; enough?



来源:https://stackoverflow.com/questions/24606988/how-do-i-send-email-using-gmail-api-php

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