使用gmail-api和google-api-php-client发送电子邮件

时间:2014-07-24 18:07:38

标签: google-api-php-client gmail-api

我正在使用https://github.com/google/google-api-php-client,我想发送一封包含用户授权的Gmail帐户的测试电子邮件。

这是我到目前为止所做的:

$msg = new Google_Service_Gmail_Message();  
$msg->setRaw('gp1');  
$service->users_messages->send('me', $msg);  

这导致退回电子邮件,因为我不知道如何设置原始邮件。我在经过身份验证的用户的收件箱中看到了反弹。我想学习如何设置电子邮件的“收件人”,“抄送”,“密件抄送”,“主题”和“正文”的值。我相信我还需要对原始数据进行64位编码。我可能想在我的电子邮件正文中使用一些html。

请帮助提供使用gmail-api和google-api-php-client发送电子邮件的工作示例。

以下是收件箱中的退回电子邮件:

  

Bounce -nobody@gmail.com- 12:58 PM(7分钟前)
  对我来说   发生错误。您的邮件未发送。

     

,日期:星期四,2014年7月24日10:58:30 -0700消息ID:CABbXiyXhRBzzuaY82i9iODEiwxEJWO1 = jCcDM_TH -

5 个答案:

答案 0 :(得分:6)

我问过a more specific question,这让我得到了答案。我现在使用PHPMailer来构建消息。然后,我从PHPMailer对象中提取原始消息。例如:

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

答案 1 :(得分:1)

我也使用过这个解决方案,通过一些调整就可以正常工作:

创建PHPMailer对象时,默认编码设置为“8bit”。 所以我不得不推翻:

$mail->Encoding = 'base64';

我要做的另一件事是稍微调整一下MIME以使其为Google API做好准备,我已经使用了ewein的解决方案:

Invalid value for ByteString error when calling gmail send API with base64 encoded < or >

无论如何,这就是我解决问题的方法:

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

答案 2 :(得分:0)

使用phpmailer创建邮件在本地环境中对我来说很好。在制作时我收到此错误:

Invalid value for ByteString

要解决此问题,请删除以下行:

$mail->Encoding = 'base64';

因为邮件是两次编码。

另外,关于其他问题/问题,我找到了下一个:

使用

strtr(base64_encode($val), '+/=', '-_*')

而不是

strtr(base64_encode($val), '+/=', '-_,')

答案 3 :(得分:0)

我用过https://developers.google.com/gmail/api/v1/reference/users/messages/send

并能够成功发送电子邮件。

答案 4 :(得分:0)

也许这超出了最初的问题,但至少在我看来,“测试电子邮件”已发展为“从”各个帐户定期发送自动欢迎电子邮件。尽管我在这里发现了很多有用的东西,但是我还是不得不从各种来源中整理东西。

为了希望帮助其他人顺利完成此过程,以下是我提出的摘要。

以下代码的一些注意事项:

  1. 这假设您已经跳过了创建和下载Google服务帐户JSON的过程(在底部的developer dashboard中,位于凭据下)。
  2. 为清楚起见,我将“您需要用自己的数据替换”部分中所有需要设置的位分组。
  3. me方法中的send()是一个关键字,它的意思是“用当前帐户发送此电子邮件”。
// This block is only needed if you're working outside the global namespace
use \Google_Client as Google_Client;
use \Google_Service_Gmail as Google_Service_Gmail;
use \Google_Service_Gmail_Message as Google_Service_Gmail_Message;

// Prep things for PHPMailer
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

// Grab the needed files
require_once 'path/to/google-api/vendor/autoload.php';
require_once 'path/to/php-mailer/Exception.php';
require_once 'path/to/php-mailer/PHPMailer.php';

// Replace this with your own data
$pathToServiceAccountCredentialsJSON = "/path/to/service/account/credentials.json";
$emailUser = "sender@yourdomain.com"; // the user who is "sending" the email...
$emailUserName = "Sending User's Name"; // ... and their name
$emailSubjectLine = "My Email's Subject Line";
$recipientEmail = "recipient@somdomain.com";
$recipientName = "Recipient's Name";
$bodyHTML = "<p>Paragraph one.</p><p>Paragraph two!</p>";
$bodyText = "Paragraph one.\n\nParagraph two!";

// Set up credentials and client
putenv("GOOGLE_APPLICATION_CREDENTIALS={$pathToServiceAccountCredentialsJSON}");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
// We're only sending, so this works fine
$client->addScope(Google_Service_Gmail::GMAIL_SEND);
// Set the user we're going to pretend to be (Subject is confusing here as an email also has a "Subject"
$client->setSubject($emailUser);

// Set up the service
$mailService = new Google_Service_Gmail($client);

// We'll use PHPMailer to build the raw email (since Google's API doesn't do that) so prep it
$mailBuilder = new PHPMailer();
$mailBuilder->CharSet = "UTF-8";
$mailBuilder->Encoding = "base64";

// Not set up the email you want to send
$mailBuilder->Subject = $emailSubjectLine;
$mailBuilder->From = $emailUser;
$mailBuilder->FromName = $emailUserName;
try {
    $mailBuilder->addAddress($recipientEmail, $recipientName);
} catch (Exception $e) {
    // Handle any problems adding the email address here
}
// Add additional recipients, CC, BCC, ReplyTo, if desired

// Then add the main body of the email...
$mailBuilder->isHTML(true);
$mailBuilder->Body = $bodyHTML;
$mailBuilder->AltBody = $bodyText;

// Prep things so we have a nice, raw message ready to send via Google's API
try {
    $mailBuilder->preSend();
    $rawMessage = base64_encode($mailBuilder->getSentMIMEMessage());
    $rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage); // url safe
    $gMessage = new Google_Service_Gmail_Message();
    $gMessage->setRaw($rawMessage);
    // Send it!
    $result = $mailService->users_messages->send('me', $gMessage);
} catch (Exception $e) {
    // Handle any problems building or sending the email here
}

if ($result->labelIds[0] == "SENT") echo "Message sent!";
else echo "Something went wrong...";