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.
Related
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();
}
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);
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());
}
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";
First of all, I know there are many library out there to do what I want to do, mainly PHPMailer and SwiftMailer.
For some reason, those two are not working with my server.
So here I am doing it from scratch.
I've found this code on the PHP documentation which is working quite fine, I would like to know how to tweak the code in order to send multiple files instead of one.
Here the code:
<?php
echo date("H:i:s");
echo mail::sendMail("to#domain.com", "Test Attach ". date("H:i:s"), "Contenu du mail <a href=3D'domain.com'>domain.com</a>", __FILE__, "xx#domain.com",'' , true);
?>
source :
<?php
class mail {
public static function prepareAttachment($path) {
$rn = "\r\n";
if (file_exists($path)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype = finfo_file($finfo, $path);
$file = fopen($path, "r");
$attachment = fread($file, filesize($path));
$attachment = chunk_split(base64_encode($attachment));
fclose($file);
$msg = 'Content-Type: \'' . $ftype . '\'; name="' . basename($path) . '"' . $rn;
$msg .= "Content-Transfer-Encoding: base64" . $rn;
$msg .= 'Content-ID: <' . basename($path) . '>' . $rn;
// $msg .= 'X-Attachment-Id: ebf7a33f5a2ffca7_0.1' . $rn;
$msg .= $rn . $attachment . $rn . $rn;
return $msg;
} else {
return false;
}
}
public static function sendMail($to, $subject, $content, $path = '', $cc = '', $bcc = '', $_headers = false) {
$rn = "\r\n";
$boundary = md5(rand());
$boundary_content = md5(rand());
// Headers
$headers = 'From: Mail System PHP <no-reply#domain.com>' . $rn;
$headers .= 'Mime-Version: 1.0' . $rn;
$headers .= 'Content-Type: multipart/related;boundary=' . $boundary . $rn;
//adresses cc and ci
if ($cc != '') {
$headers .= 'Cc: ' . $cc . $rn;
}
if ($bcc != '') {
$headers .= 'Bcc: ' . $cc . $rn;
}
$headers .= $rn;
// Message Body
$msg = $rn . '--' . $boundary . $rn;
$msg.= "Content-Type: multipart/alternative;" . $rn;
$msg.= " boundary=\"$boundary_content\"" . $rn;
//Body Mode text
$msg.= $rn . "--" . $boundary_content . $rn;
$msg .= 'Content-Type: text/plain; charset=ISO-8859-1' . $rn;
$msg .= strip_tags($content) . $rn;
//Body Mode Html
$msg.= $rn . "--" . $boundary_content . $rn;
$msg .= 'Content-Type: text/html; charset=ISO-8859-1' . $rn;
$msg .= 'Content-Transfer-Encoding: quoted-printable' . $rn;
if ($_headers) {
$msg .= $rn . '<img src=3D"cid:template-H.PNG" />' . $rn;
}
//equal sign are email special characters. =3D is the = sign
$msg .= $rn . '<div>' . nl2br(str_replace("=", "=3D", $content)) . '</div>' . $rn;
if ($_headers) {
$msg .= $rn . '<img src=3D"cid:template-F.PNG" />' . $rn;
}
$msg .= $rn . '--' . $boundary_content . '--' . $rn;
//if attachement
if ($path != '' && file_exists($path)) {
$conAttached = self::prepareAttachment($path);
if ($conAttached !== false) {
$msg .= $rn . '--' . $boundary . $rn;
$msg .= $conAttached;
}
}
//other attachement : here used on HTML body for picture headers/footers
if ($_headers) {
$imgHead = dirname(__FILE__) . '/../../../../modules/notification/ressources/img/template-H.PNG';
$conAttached = self::prepareAttachment($imgHead);
if ($conAttached !== false) {
$msg .= $rn . '--' . $boundary . $rn;
$msg .= $conAttached;
}
$imgFoot = dirname(__FILE__) . '/../../../../modules/notification/ressources/img/template-F.PNG';
$conAttached = self::prepareAttachment($imgFoot);
if ($conAttached !== false) {
$msg .= $rn . '--' . $boundary . $rn;
$msg .= $conAttached;
}
}
// Fin
$msg .= $rn . '--' . $boundary . '--' . $rn;
// Function mail()
mail($to, $subject, $msg, $headers);
}
}
?>
Where it says: FILE that where I've put the file name.
How do I do it so I can put more than one file.
Thank you.
Using the mail() for attachments is a little more complex than that. You got to tell mail() which part should handle the file attachment and which part is responsible to display the email body by setting up a MIME Boundary. In other words, the code should be divided into 2 parts:
A section to handle the message being sent in body
A section to handle file uploading
A detailed tutorial is here
PHP EMAIL WITH ATTACHMENT
However, I would suggest you to use a very handy tool called PHPMailer to do the same task. It simplifies the process and lets the class handle all the legwork.
PHPMailer
ref : Attach File Through PHP Mail