4

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. Commented Jul 19, 2017 at 21:22
  • Where you able to solve this? Commented Feb 2, 2018 at 5:20

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

3 Comments

I am confused. Where do I add the To, CC or BCC in the code I have mentioned. Could you add a code snippet?
Did you ever find the solution to this?
Nope. I dropped the plan and moved to zapier. You can try this zapier.com/apps/gmail/integrations
0

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.