sending mail with attachment using gmail api in php - php

When I'm trying to send mail using php.text also send as an attachment with the name noname.html. please provide a solution for me.
I have used this library to send email https://github.com/google/google-api-php-client. My code is like this.any help will be appreciated.
$client->setAccessToken($_SESSION['gmail_access_token']);
$objGMail = new Google_Service_Gmail($client);
$strMailContent = 'This is a test mail which is <b>sent via</b> using Gmail API client library.<br/><br/><br/>Thanks,<br/><b>Premjith K.K..</b>';
// $strMailTextVersion = strip_tags($strMailContent, '');
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strToMailName = 'NAME';
$strToMail = 'name#gmail.com';
$strSesFromName = 'Premjith GMAIL API';
$strSesFromEmail = 'premji341800#gmail.com';
$strSubject = 'Test mail using GMail API - with attachment - ' . date('M d, Y h:i:s A');
$strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n";
$strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n";
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
$filePath = 'abc.pdf';
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mimeType = finfo_file($finfo, $filePath);
$fileName = 'abc.pdf';
$fileData = base64_encode(file_get_contents($filePath));
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";
$strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
$strRawMessage .= '--' . $boundary . "\r\n";
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/plain; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n";
// $strRawMessage .= $strMailTextVersion . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= $strMailContent . "\r\n";
//Send Mails
//Prepare the message in message/rfc822
try {
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$objSentMsg = $objGMail->users_messages->send("me", $msg);
print('Message sent object');
// print($objSentMsg);
} catch (Exception $e) {
print($e->getMessage());
unset($_SESSION['access_token']);
}
When I change the code line
$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
to
$strRawMessage .= 'Content-type: Multipart/Alternative; boundary="' . $boundary . '"' . "\r\n"; Mail Send as html only with out attachment. Please help me

I have change my code like this its worked fine for me. Thank you all for the support.
$client->setAccessToken($_SESSION['gmail_access_token']);
$objGMail = new Google_Service_Gmail($client);
$strMailContent = 'This is a test mail which is <b>sent via</b> using Gmail API client library.<br/><br/><br/>Thanks,<br/><b>Premjith K.K..</b>';
// $strMailTextVersion = strip_tags($strMailContent, '');
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strToMailName = 'NAME';
$strToMail = 'name#gmail.com';
$strSesFromName = 'Premjith GMAIL API';
$strSesFromEmail = 'premji341800#gmail.com';
$strSubject = 'Test mail using GMail API - with attachment - ' . date('M d, Y h:i:s A');
$strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n";
$strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n";
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
$filePath = 'abc.pdf';
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mimeType = finfo_file($finfo, $filePath);
$fileName = 'abc.pdf';
$fileData = base64_encode(file_get_contents($filePath));
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";
$strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= $strMailContent . "\r\n";
//Send Mails
//Prepare the message in message/rfc822
try {
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$objSentMsg = $objGMail->users_messages->send("me", $msg);
print('Message sent object');
// print($objSentMsg);
} catch (Exception $e) {
print($e->getMessage());
unset($_SESSION['access_token']);
}

The above code works fine for a single attachment.
If you want to send multiple attachments just follow this code this allowed to send your mail body part with multiple attachments.
$client->setAccessToken($_SESSION['gmail_access_token']);
$objGMail = new Google_Service_Gmail($client);
$strMailContent = 'This is a test mail which is <b>sent via</b> using Gmail API client library.<br/><br/><br/>Thanks,<br/><b>Premjith K.K..</b>';
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strToMailName = 'NAME';
$strToMail = 'name#gmail.com';
$strSesFromName = 'Premjith GMAIL API';
$strSesFromEmail = 'premji341800#gmail.com';
$strSubject = 'Test mail using GMail API - with attachment - ' . date('M d, Y h:i:s A');
$strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n";
$strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n";
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$strRawMessage .= "Content-Transfer-Encoding: base64" . "\r\n\r\n";
$strRawMessage .= $sentMailData->body . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
foreach ($files as $key => $filePath) {
if($filePath!=""){
$array = explode('/', $filePath);
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mimeType = finfo_file($finfo, $filePath);
$fileName = $array[sizeof($array)-1];
$fileData = base64_encode(file_get_contents($filePath));
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";
$strRawMessage .= 'Content-ID: <' . $sentMailData->email. '>' . "\r\n";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
}
}
//Send Mails
//Prepare the message in message/rfc822
try {
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$objSentMsg = $service->users_messages->send("me", $msg);
echo '<pre>'; print_r($objSentMsg); echo '</pre>';
if($sentMailData->attachments!=""){
$files = explode(',', $sentMailData->attachments);
foreach ($files as $key => $filePath) {
if($filePath!=""){
#unlink($filePath);
}
}
}
echo '<pre>'; print_r($sentMailData); echo '</pre>';
} catch (Exception $e) {
print($e->getMessage());
}

Related

GMail API "Request Entity Too Large Error 413" for attachment larger than 5MB

I have reviewed some similar questions on stackoverflow, but none of the answers seem to be working for me. Especially I have tried the options ['uploadType' => 'multipart'] and ['uploadType' => 'resumable'] when sending email. It always gives "Request Entity Too Large Error 413" if the attachment is over 5MB (I tried sending a docx file of 7.x MB and failed). For attachment smaller than 5MB it's OK. Could anyone please help? Many thanks!
Here is my code:
$objGMail = new Google_Service_Gmail($client);
$strSubject = "Test message";
$strRawMessage = "From: <mygmailid#gmail.com>\r\n";
$strRawMessage .= "To: <receiveremailid#gmail.com>\r\n";
$strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= "MIME-Version: 1.0\r\n";
$boundary = uniqid(rand(), true);
$strRawMessage .= 'Content-type: multipart/related; boundary="' . $boundary . '"' . "\r\n";
$filePath = "data/bigdocfile.docx";
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mimeType = finfo_file($finfo, $filePath);
$fileName = "bigdocfile.docx";
$fileData = base64_encode(file_get_contents($filePath));
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";
$strRawMessage .= 'Content-ID: <mygmailid#gmail.com' . '>' . "\r\n";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
$strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= $order->content;
try
{
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$objSentMsg = $objGMail->users_messages->send("me", $msg, ['uploadType' => 'multipart']);
return "success";
} catch (Exception $e) {
unset($_SESSION['gmail_access_token']);
return $e->getMessage();
}

Attachment gets duplicated in apple mail client when mail sent through the gmail api php code

I am using the Gmail Api code in php to send mails to clients. The mail contains multiple attachments and all works good except for the clients who are using the apple mail app. They see the duplicated attachments. That is if the mail has 4 different attachments, all they see in apple mail app is 4 same duplicated attachments. Please see my code below.
$objGMail = new Google_Service_Gmail($this->googleauth->client);
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strRawMessage .= 'To: ' .$toEmailsName . " <" . $ToEmail . ">" . "\r\n";
$strRawMessage .= 'Cc: ' .$ccEmailsName . " <" . $CcEmail . ">" . "\r\n";
$strRawMessage .= 'Bcc: ' .$BccEmailsName . " <" . $BccEmail . ">" . "\r\n";
$strRawMessage .= 'From: '.$fromName . " <" . $fromEmail . ">" . "\r\n";
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($EmailSubject) . "?=\r\n";
$strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Attachments
if (isset($post['UploadedFileName'])) {
for ($i = 0; $i < count($post['UploadedFileName']); $i++) {
if ($post['UploadedFileName'][$i] <> "") {
$filePath = './attachments/' . $post['UploadedFileName'][$i];
$mimeType = finfo_file($finfo, $filePath);
$fileName = $post['UploadedFileName'][$i];
$fileData = chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";
$strRawMessage .= 'Content-ID: <' . $fromEmail . '>' . "\r\n";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= $fileData;
$strRawMessage .= "--{$boundary}\r\n";
}
}
}
$strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= $EmailBody . "\r\n";
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$objSentMsg = $objGMail->users_messages->send("me", $msg);

Getting Request Entity Too Large error 413 while sending attachment over 5 MB size using Gmail API in php

Error :
Fatal error: Uncaught Google_Service_Exception:
Request Entity Too Large Request Entity Too Large
Error 413 in
C:\xampp\htdocs\gmail\vendor\google\apiclient\src\Google\Http\REST.php:118
Stack trace: #0
C:\xampp\htdocs\gmail\vendor\google\apiclient\src\Google\Http\REST.php(94):
Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1
C:\xampp\htdocs\gmail\vendor\google\apiclient\src\Google\Task\Runner.php(176):
Google_Http_REST::doExecute(Object(GuzzleHttp\Client),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2
C:\xampp\htdocs\gmail\vendor\google\apiclient\src\Google\Http\REST.php(58):
Google_Task_Runner->run() #3
C:\xampp\htdocs\gmail\vendor\google\apiclient\src\Google\Client.php(798):
Google_Http_REST::execute(Object(GuzzleHttp\Client),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...', Array) #4
C:\xampp\htdocs\gmail\vendor\ in
C:\xampp\htdocs\gmail\vendor\google\apiclient\src\Google\Http\REST.php
on line 118
Code :$strRawMessage .= 'To: ' . encodeRecipients(" <" . $strToMail .
">") . "\r\n"; $strRawMessage .= 'Subject: =?utf-8?B?' .
base64_encode($strSubject) . "?=\r\n"; $strRawMessage .=
"MIME-Version: 1.0\r\n"; $strRawMessage .= 'Content-type: resumable;
boundary="' . $boundary . '"' . "\r\n"; $strRawMessage .=
'Content-Transfer-Encoding: chunked' . "\r\n\r\n";
/*************Attachment**************/ $basename =
basename($filePath); $fileTempPath = sys_get_temp_dir() . "/" .
$basename; file_put_contents($fileTempPath,
file_get_contents($filePath)); $finfo =
finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype
extension $mimeType = finfo_file($finfo, $fileTempPath); $fileData =
base64_encode(file_get_contents($fileTempPath)); $strRawMessage .=
"\r\n--{$boundary}\r\n"; $strRawMessage .= 'Content-Type: ' .
$mimeType . '; name="' . $basename . '";' . "\r\n"; //$strRawMessage
.= 'Content-Type: message/rfc822 ' . "\r\n"; $strRawMessage .=
'Content-ID: <' . $basename . '>' . "\r\n"; $strRawMessage .=
'Content-Length: ' . filesize($fileTempPath) . "\r\n"; $strRawMessage
.= 'X-Upload-Content-Type: message/rfc822' . "\r\n"; $strRawMessage
.= 'X-Upload-Content-Length: ' . filesize($fileTempPath) . "\r\n";
$strRawMessage .= 'Content-Description: ' . $basename . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' .
$basename . '"; size=' . filesize($fileTempPath) . ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: chunked' . "\r\n\r\n";
$strRawMessage .= chunk_split($fileData, 76, "\r\n") . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
/*************Attachment**************/
$strRawMessage .= "--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: application/json; charset=' . $charset . "\r\n";
//$strRawMessage .= 'Content-Transfer-Encoding: 8bit' . "\r\n\r\n";
$strRawMessage .= $strMessage . "\r\n";
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$message->setRaw($mime);
$messagesResponse = $service->users_messages->send('me', $message, ['uploadType' => 'resumable ']);

Gmail API file attachments not shown on receiver side

I have some Gmail API PHP code which sends an email with attachments. Attachments dispatch on sender side perfectly, even they are available in sender's sent items. But they did not show on receiver end. what could be the problem? my code looks like following.
$to = $_POST['replyTo'];
$message = $_POST['replyMsg'];
$thread_id = $_POST['thread_id'];
$subject = $_POST['MsgSubject'];
$cc = $_POST['cc'];
$bcc = $_POST['bcc'];
$strCCName = '';
$strBCCName = '';
if (!empty($cc)) {
$encodedCC = "";
if (strpos($cc, ",") !== false) {
$list = explode(",", $cc);
foreach ($list as $ccmail) {
$encodedCC .= encodeRecipients($strCCName . " <" . $ccmail . ">") . ",";
}
} else {
$encodedCC = encodeRecipients($strCCName . " <" . $cc . ">");
}
}
if (!empty($bcc)) {
$encodedBCC = "";
if (strpos($bcc, ",") !== false) {
$list = explode(",", $bcc);
foreach ($list as $bccmail) {
$encodedBCC .= encodeRecipients($strCCName . " <" . $bccmail . ">") . ",";
}
} else {
$encodedCC = encodeRecipients($strCCName . " <" . $bcc . ">");
}
}
$strMailContent = $message;
$strMailTextVersion = strip_tags($strMailContent, '');
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strToMailName = '';
$strToMail = $to;
$strSesFromName = $_SESSION['userData']['first_name']." ".$_SESSION['userData']['last_name'];
$strSesFromEmail = $_SESSION['userData']['email'];
$strSubject = $subject;
$strRawMessage .= 'To: ' . encodeRecipients($strToMailName . " <" . $strToMail . ">") . "\r\n";
$strRawMessage .= 'From: '. encodeRecipients($strSesFromName . " <" . $strSesFromEmail . ">") . "\r\n";
if (!empty($cc)) {
$strRawMessage .= 'Cc: ' . $encodedCC . "\r\n";
}
if (!empty($bcc)) {
$strRawMessage .= 'Bcc: ' . $encodedBCC . "\r\n";
}
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
$strRawMessage .= 'Content-type: Multipart/Alternative; boundary="' . $boundary . '"' . "\r\n";
/**** check if message contains any attachments *****/
if(count($_FILES['attachment']['name']) > 0){
//Loop through each file
for($i=0; $i<count($_FILES['attachment']['name']); $i++) {
$j=$i+1;
//Get the temp file path
$filePath = $_FILES['attachment']['tmp_name'][$i];
//Make sure we have a filepath
if($filePath != ""){
$fileName=$_FILES['attachment']['name'][$i];
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mimeType = finfo_file($finfo, $filePath);
$fileData = base64_encode(file_get_contents($filePath));
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";
$strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
$strRawMessage .= '--' . $boundary . "\r\n";
}
}
}
/*****/
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/plain; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n";
$strRawMessage .= $strMailTextVersion . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= $strMailContent . "\r\n";
try {
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$msg->setThreadId($thread_id);
$objSentMsg = $service->users_messages->send("me", $msg);
echo "msg sent!";
} catch (Exception $e) {
print($e->getMessage());
}
its been couple of hours messing around but didn't find anything. Can anyone help me out of this? Thanks.

Send Mail with attachment using Gmail new API, but it is not displayed for receiver's inbox

We are integrating GMail using the latest API provided by them as a part of developing email client within our application. We are using PHP client library provided by Google.
See the link https://developers.google.com/api-client-library/php/
In this I'm trying to send a mail with attachment. Here we have generated message/rfc822 compatible text and passed it with 'raw' parameter. Here the problem I found is, after executing the code, when I checked the sent mail for the mail which I sent via GMail API, the attachments are shown correctly. But it is not received/ displayed for the sender's mail box.
See the code for more info:
require_once DOCUMENT_ROOT . '/../library/google/src/Google/Client.php';
require_once DOCUMENT_ROOT . '/../library/google/src/Google/Service/Gmail.php';
function encodeRecipients($recipient){
$recipientsCharset = 'utf-8';
if (preg_match("/(.*)<(.*)>/", $recipient, $regs)) {
$recipient = '=?' . $recipientsCharset . '?B?'.base64_encode($regs[1]).'?= <'.$regs[2].'>';
}
return $recipient;
}
$isAccessCodeExpired = 0;
$arrAccessToken = array();
$session = new Zend_Session_Namespace();
$client = new Google_Client();
$client->setClientId($this->client_id);
$client->setClientSecret($this->client_secret);
$client->setRedirectUri($this->redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope("https://mail.google.com/");
$client->addScope("https://www.googleapis.com/auth/gmail.compose");
$client->addScope("https://www.googleapis.com/auth/gmail.modify");
$client->addScope("https://www.googleapis.com/auth/gmail.readonly");
if ($this->getRequest()->getParam('code')) {
$code = $this->getRequest()->getParam('code');
$client->authenticate($code);
$session->gmail_access_token = $client->getAccessToken();
//$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$redirect = BASE_PATH . '/oauth2callback';
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
$isAccessCodeExpired = $client->isAccessTokenExpired();
if (isset($session->gmail_access_token) && $session->gmail_access_token != "" && $isAccessCodeExpired !== 1) {
$client->setAccessToken($session->gmail_access_token);
$objGMail = new Google_Service_Gmail($client);
$strMailContent = 'This is a test mail which is sent via using Gmail API client library.<br/><br/><br/>Thanks,<br/>GMail API Team.';
$strMailTextVersion = strip_tags($strMailContent, '');
$strRawMessage = "";
$boundary = uniqid(rand(), true);
$subjectCharset = $charset = 'utf-8';
$strToMailName = 'To User Name';
$strToMail = 'toemail#gmail.com';
$strSesFromName = 'From User Name';
$strSesFromEmail = 'fromemail#gmail.com';
$strSubject = 'Test mail using GMail API - with attachment - ' . date('M d, Y h:i:s A');
$strRawMessage .= 'To: ' . encodeRecipients($strToMailName . " <" . $strToMail . ">") . "\r\n";
$strRawMessage .= 'From: '. encodeRecipients($strSesFromName . " <" . $strSesFromEmail . ">") . "\r\n";
$strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
$strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
$strRawMessage .= 'Content-type: Multipart/Alternative; boundary="' . $boundary . '"' . "\r\n";
$filePath = '/home/server/Downloads/credentials.csv';
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
$mimeType = finfo_file($finfo, $filePath);
$fileName = 'credentials.csv';
$fileData = base64_encode(file_get_contents($filePath));
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";
$strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";
$strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
$strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
$strRawMessage .= '--' . $boundary . "\r\n";
$strRawMessage .= "\r\n--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/plain; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: 7bit' . "\r\n\r\n";
$strRawMessage .= $strMailTextVersion . "\r\n";
$strRawMessage .= "--{$boundary}\r\n";
$strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
$strRawMessage .= $strMailContent . "\r\n";
//Send Mails
//Prepare the message in message/rfc822
try {
// The message needs to be encoded in Base64URL
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$objSentMsg = $objGMail->users_messages->send("me", $msg);
print('Message sent object');
print($objSentMsg);
} catch (Exception $e) {
print($e->getMessage());
unset($_SESSION['access_token']);
}
}
Please help me...
Thanks in advance.
Replace your:
$strRawMessage .= 'Content-type: Multipart/Alternative; boundary="' . $boundary . '"' . "\r\n";
with:
$strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";

Categories