4
votes

I have a working gmail api php code grabbed from https://github.com/google/google-api-php-client/

I am able to send email with the following code but without a recipient. In gmail sent items I can also see the message sent!

$mime = rtrim(strtr(base64_encode($_POST["message"]), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$x = $service->users_messages->send("me", $msg);

How do I add a recipient email address? In few posts I read that To should be added to the header.

2
Did this ever get resolved? I'm getting the "Recipient address required" error, but I've set the "To" value.Quasipickle
Where you able to solve this?Ashit Vora

2 Answers

0
votes

Yes, add To, Cc, or Bcc headers to the email message to send the email to people. In your case, the $_POST["message"] string or even better yet some email message object using a standard php email library.

See: https://developers.google.com/gmail/api/v1/reference/users/messages/send https://developers.google.com/gmail/api/guides/sending

0
votes

You should pass a raw email to \Google_Service_Gmail_Message() class. This raw message should be a mime message base64 encoded. Pretty much everything you did.

BUT: you need not to pass the email body (like the content of the email address), but literally the whole email - with headers. So not $_POST["message"] should be passed, but a prepared email that has all the required headers, including TO, FROM etc. Here is an example:

From: [email protected]
To: [email protected]
Subject: YOUR CUSTOM SUBJECT
Content-Type: text/plain; charset=UTF-8
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary=5ae50a40c56153a0ca99d08aaf8f99d53f63981962d4f199b2339614636b

--5ae50a40c56153a0ca99d08aaf8f99d53f63981962d4f199b2339614636b
YOUR CUSTOM EMAIL CONTENT GOES HERE. Might be a mix of html and plain text.
--5ae50a40c56153a0ca99d08aaf8f99d53f63981962d4f199b2339614636b--

It's much better to use something like PHPMailer class to prepare the whole MIME version of the email for you, where you just pass to its public methods required data, subject, FROM, TO, body etc - and then request a MIME with a single method like this $phpmailer->getSentMIMEMessage().