codeigniter html email changing characters - php

i have a problem with emails the html is ok but when i open them there are errors in the text and the links some chars where changed into = like
Thanks for joining . your log=n details are here ma=e sure you keep them safe.
To verify your email address, please follow this link:
Finish your registration...
Link doesn't work? Copy the following link to your browser address bar: http://www.myurl.com/dev=l/panel/auth/activate/123131/123131
Please verify your email within 123131 hours, otherwise your registration =ill become invalid and you will have to register again.
every image and link even the text is borken up
i was thinkin that it has someting to do with {unwrap} but did not help
this is the config/email.php
$config['email_notification']['protocol'] = 'smtp';
$config['email_notification']['smtp_host'] = 'smtp.live.com';
$config['email_notification']['smtp_user'] = 'xxxxx';
$config['email_notification']['smtp_pass'] = 'xxxxxxx';
$config['email_notification']['smtp_port'] = '587';
$config['email_notification']['mailtype'] = 'html';
$config['email_notification']['charset'] = 'utf-8';
$config['email_notification']['wordwrap'] = false;
$config['email_notification']['smtp_crypto'] = 'tls';
this is the controller
$this->load->library('email');
$this->email->initialize($this->config->item('email_notification'));
$this->email->subject('Email Test');
$this->email->set_newline("\r\n");
$this->email->from('xxxxxx'); // change it to yours
$this->email->to('xxxxx');
$this->email->subject('Email Test');
$data=array(
'site_name'=>'tralalalal',
'user_id'=>'123131',
'new_email_key'=>'123131',
'activation_period'=>'123131',
'email'=>'123131',
'title'=>'123131',
);
$this->email->message($this->load->view('email/activate_account/en',$data,true));
the email body is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
/* Client-specific Styles */
#outlook a{padding:0;} /* Force Outlook to provide a "view in browser" button. */
body{width:100% !important;} .ReadMsgBody{width:100%;} .ExternalClass{width:100%;} /* Force Hotmail to display emails at full width */
body{-webkit-text-size-adjust:none;} /* Prevent Webkit platforms from changing default text sizes. */
/* Reset Styles */
body{margin:0; padding:0;}
img{border:0; height:auto; line-height:100%; outline:none; text-decoration:none;}
table td{border-collapse:collapse;}
#backgroundTable{height:100% !important; margin:0; padding:0; width:100% !important;}
</style>
</head>
<body>
thanks

i found the answer so if anyone have the same problem
there is why
There are two limits that this standard places on the number of
characters in a line. Each line of characters MUST be no more than
998 characters, and SHOULD be no more than 78 characters, excluding
the CRLF.
The 998 character limit is due to limitations in many
implementations which send, receive, or store Internet Message
Format messages that simply cannot handle more than 998 characters
on a line. Receiving implementations would do well to handle an
arbitrarily large number of characters in a line for robustness
sake. However, there are so many implementations which (in
compliance with the transport requirements of [RFC2821]) do not
accept messages containing more than 1000 character including the
CR and LF per line, it is important for implementations not to
create such messages.
The more conservative 78 character recommendation is to accommodate
the many implementations of user interfaces that display these
messages which may truncate, or disastrously wrap, the display of
more than 78 characters per line, in spite of the fact that such
implementations are non-conformant to the intent of this
specification (and that of [RFC2821] if they actually cause
information to be lost). Again, even though this limitation is put on
messages, it is encumbant upon implementations which display messages
and this is where you change the code to overwrite this limit
system/libraries/email.php
ORGINAL
protected function _prep_quoted_printable($str, $charlim = '')
{
// Set the character limit
// Don't allow over 76, as that will make servers and MUAs barf
// all over quoted-printable data
if ($charlim == '' OR $charlim > '76')
{
$charlim = '76';
}
QUICK FIX :)
protected function _prep_quoted_printable($str, $charlim = '')
{
// Set the character limit
// Don't allow over 76, as that will make servers and MUAs barf
// all over quoted-printable data
if ($charlim == '' OR $charlim > '76')
{
$charlim = '200';
}

I think the problem is in the _prep_quoted_printable function. Luckily there is a native PHP version of this function as of v5.3
I was able to solve a similar issue by replacing instances of _prep_quoted_printable in the Email class with the PHP native function quoted_printable_encode.
This amounted to my _build_message() looking like this:
/**
* Build Final Body and attachments
*
* #access protected
* #return void
*/
protected function _build_message()
{
if ($this->wordwrap === TRUE AND $this->mailtype != 'html')
{
$this->_body = $this->word_wrap($this->_body);
}
$this->_set_boundaries();
$this->_write_headers();
$hdr = ($this->_get_protocol() == 'mail') ? $this->newline : '';
$body = '';
switch ($this->_get_content_type())
{
case 'plain' :
$hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
$hdr .= "Content-Transfer-Encoding: " . $this->_get_encoding();
if ($this->_get_protocol() == 'mail')
{
$this->_header_str .= $hdr;
$this->_finalbody = $this->_body;
}
else
{
$this->_finalbody = $hdr . $this->newline . $this->newline . $this->_body;
}
return;
break;
case 'html' :
if ($this->send_multipart === FALSE)
{
$hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
$hdr .= "Content-Transfer-Encoding: quoted-printable";
}
else
{
$hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline . $this->newline;
$body .= $this->_get_mime_message() . $this->newline . $this->newline;
$body .= "--" . $this->_alt_boundary . $this->newline;
$body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
$body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
$body .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
$body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
$body .= "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline;
}
// $this->_finalbody = $body . $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline;
$this->_finalbody = $body . quoted_printable_encode($this->_body) . $this->newline . $this->newline;
if ($this->_get_protocol() == 'mail')
{
$this->_header_str .= $hdr;
}
else
{
$this->_finalbody = $hdr . $this->_finalbody;
}
if ($this->send_multipart !== FALSE)
{
$this->_finalbody .= "--" . $this->_alt_boundary . "--";
}
return;
break;
case 'plain-attach' :
$hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
if ($this->_get_protocol() == 'mail')
{
$this->_header_str .= $hdr;
}
$body .= $this->_get_mime_message() . $this->newline . $this->newline;
$body .= "--" . $this->_atc_boundary . $this->newline;
$body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
$body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
$body .= $this->_body . $this->newline . $this->newline;
break;
case 'html-attach' :
$hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline;
if ($this->_get_protocol() == 'mail')
{
$this->_header_str .= $hdr;
}
$body .= $this->_get_mime_message() . $this->newline . $this->newline;
$body .= "--" . $this->_atc_boundary . $this->newline;
$body .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline;
$body .= "--" . $this->_alt_boundary . $this->newline;
$body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
$body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
$body .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;
$body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
$body .= "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline;
// $body .= $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline;
$body .= quoted_printable_encode($this->_body) . $this->newline . $this->newline;
$body .= "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline;
break;
}
$attachment = array();
$z = 0;
for ($i=0; $i < count($this->_attach_name); $i++)
{
$filename = $this->_attach_name[$i];
$basename = basename($filename);
$ctype = $this->_attach_type[$i];
if ( ! file_exists($filename))
{
$this->_set_error_message('lang:email_attachment_missing', $filename);
return FALSE;
}
$h = "--".$this->_atc_boundary.$this->newline;
$h .= "Content-type: ".$ctype."; ";
$h .= "name=\"".$basename."\"".$this->newline;
$h .= "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline;
$h .= "Content-Transfer-Encoding: base64".$this->newline;
$attachment[$z++] = $h;
$file = filesize($filename) +1;
if ( ! $fp = fopen($filename, FOPEN_READ))
{
$this->_set_error_message('lang:email_attachment_unreadable', $filename);
return FALSE;
}
$attachment[$z++] = chunk_split(base64_encode(fread($fp, $file)));
fclose($fp);
}
$body .= implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
if ($this->_get_protocol() == 'mail')
{
$this->_finalbody = $body;
}
else
{
$this->_finalbody = $hdr . $body;
}
return;
}

Have a closed environment with Outlook and no expectation of sending to another mail client.
Similar result but different version of codeigniter.
The one I have has a wrapchars variable to allow it to change.
The thing is it was using a hardcoded 76 in _prep_quoted_printable.
I changed the 76 to
$this->wrapchars
and all became good in the world.

Related

Send Email with attachment by using URL in Codeigniter

I would like to send an email with attachment.
I have no problem to send an email by using file path, but I prefer to set my attachment by using URL.
The email can sent successfully to my email without any attachment.
My PDF URL example: http://store/index.php/Store/GI/OrderID.pdf
Hope some can help me. Really Appreciate. Thank You.
Controller::
public function SendInvoice(){
$orderid = $this->uri->segment(3);
$result = $this->order->GetCustOrder($orderid);
unset($data);
$data = array(
$OrderID,
$result[0]->cust_id,
$result[0]->cust_name,
$result[0]->cust_email
);
$this->store_email->SendInvoiceToCust($data); //library
$this->session->set_flashdata('sent_email','Email has been sent to customer.');
redirect('Store/Index');
}
Library::
public function SendInvoiceToCust($data){
$message = "Dear Valued Customer, <br><br>Thank you for Purchased at Store. <br/><br/>Kindly refer the attachment to view your Invoice.";
//$attached_file = base_url(). 'index.php/Store/GI/' .$data[0]. '.pdf';
$form = base_url(). 'index.php/Store/GI/' .$data[0]. '.pdf';
$attachment = chunk_split(base64_encode($form));
$separator = md5(time());
$message .= "--" . $separator . PHP_EOL;
$message .= "Content-Type: application/octet-stream; name=\"\" . $data[0]. '.pdf'\"" . PHP_EOL;
$message .= "Content-Transfer-Encoding: base64" . PHP_EOL;
$message .= "Content-Disposition: attachment" . PHP_EOL . PHP_EOL;
$message .= $attachment . PHP_EOL . PHP_EOL;
$message .= "--" . $separator . "--";
$this->email->from('email#gmail.com', 'Store');
$this->email->to('email2#gmail.com');
$this->email->subject('Store INVOICE [Do not reply]');
$this->email->message($message);
$this->email->attach($attachment);
$this->email->send();
}
I cant comment yet but you should try setting content type and encoding the pdf.
The below is what I am currently using to send out an email with an attachement in codeigniter.
I have updated the response. This is currently how I am taking a pdf form and attaching it.
Its all done within the $message field with different content transfer and types being set.
$sender = "email#gmail.com";
$emails = "email2#gmail.com";
$subject = "Store INVOICE [Do not reply]";
$headers = "From: " . $sender . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$message = "";
$message = "--" . $separator . PHP_EOL;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"" . PHP_EOL;
$message .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$message .= ($content = "Dear Valued Customer, <br><br>Thank you for Purchased at Store. <br/><br/>Kindly refer the attachment to view your Invoice.");
$message .= PHP_EOL . PHP_EOL;
$form = base_url(). 'index.php/Store/GI/' .$data[0]. '.pdf';
$attachment = chunk_split(base64_encode($form));
$separator = md5(time());
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 7bit";
$message .= "--" . $separator . PHP_EOL;
$message .= "Content-Type: application/octet-stream; name=\"" . $data[0]. '.pdf'\"" . PHP_EOL;
$message .= "Content-Transfer-Encoding: base64" . PHP_EOL;
$message .= "Content-Disposition: attachment" . PHP_EOL . PHP_EOL;
$message .= $attachment . PHP_EOL . PHP_EOL;
$message .= "--" . $separator . "--";
$result = mail($emails, $subject, $message, $headers);

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.

loosing part of image during mail delivery

I've got a problem sending email with php. The first line of my base64 encoded image disappears during mail delivery. What am I doing wrong here?
This is part of the printed message before sending:
...
--67e5a910fa8cffc2b52b2aec743f9332
Content-Disposition: attachment
Content-Type: image/svg; name="aaa.svg"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="aaa.svg"
PHN2ZyB2aWV3Qm94PSIwIDAgMjk2NjkgMjA5OTAiIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcv
ZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25z
...
This is the message i receive:
...
--67e5a910fa8cffc2b52b2aec743f9332
Content-Disposition: attachment
Content-Type: image/svg; name="aaa.svg"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="aaa.svg"
ZGMvZWxlbWVudHMvMS4xLyIgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25z
...
my code:
<?php
if($_POST) {
date_default_timezone_set('Europe/Berlin');
$uid = md5(uniqid(time()));
$eol = PHP_EOL;
$name = $_POST['name'];
$gliderName = $_POST['glider'];
$gliderSize = $_POST['size'];
$subject = $gliderName . "_" . $gliderSize . "_" . $name . "_" . date('d-m-Y_h:i:s', time());
$subject = str_replace(' ', '_', $subject);
$comment = $_POST['comment'];
$attachment = $_POST['image'];
$sendToSwing = $_POST['sendToSwing'];
$mail = $_POST['email'];
$mail_to = $mail;
if ($sendToSwing) {
$mail_to .= "," . "ZIELADRESSE#aaa.DE";
}
$mail_from = "ABSENDERADRESSE#aaa.DE";
$from_name = "ABSENDERNAME";
$header = "From: " . $from_name . " <" . $mail_from . ">" . $eol;
$header .= "Reply-To: " . $mail_from.$eol;
$header .= "MIME-Version: 1.0" . $eol;
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"" . $eol . $eol;
$msg = '<html><head><title>' . $subject . '</title></head><body>' . $eol;
$msg .= '<b>glider:</b> ' . $gliderName . $eol;
$msg .= '<b>size:</b> ' . $gliderSize . $eol;
$msg .= '<b>customer name:</b> ' . $name . $eol;
$msg .= '<b>customer email:</b> ' . $mail . $eol;
$msg .= '<b>message from customer:</b> ' . $comment . $eol;
$msg .= '</body></html>' . $eol;
$message = "--" . $uid . $eol;
$message .= "Content-type:text/html; charset=utf-8" . $eol;
$message .= "Content-Transfer-Encoding: utf-8" . $eol . $eol;
$message .= $msg . $eol;
// attachment
//echo $eol.$attachment.$eol;
$attachment = chunk_split(base64_encode($attachment));
//echo $eol.$attachment.$eol;
$message .= "--" . $uid . $eol;
$message .= "Content-Type: image/svg; name=\"" . $subject . ".svg\"" . $eol;
$message .= "Content-Transfer-Encoding: base64" .$eol;
$message .= "Content-Disposition: attachment; filename=\"" . $subject . ".svg\"" . $eol;
$message .= $attachment . $eol;
$message .= "--".$uid."--";
echo $eol.$message.$eol;
if (mail($mail_to, $subject, $message, $header)) {
echo "success ";
} else {
echo "error sending email";
}
}
?>
Like this it should work (two new line before the payload):
$message .= "Content-Disposition: attachment; filename=\"" . $subject . ".svg\"" . $eol.$eol;

Include multiple attachment by mail PHP

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

What is wrong with this mail header text?

The following $header is being sent via PHP's mail($to,$subject,$content,$header) command. The mail arrives and appears to have an attachment. But the mail text is empty as is the file. I think this has something to do with line spacing but I can't see the problem. I have tried putting the contents (between the boundaries) in $contents rather than appending it to $header. It doesn't make a difference. Any thoughts?
From: dnagirl#someplace.com
Reply-To: dnagirl#someplace.com
X-Mailer: PHP 5.3.1
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="7425195ade9d89bc7492cf520bf9f33a"
--7425195ade9d89bc7492cf520bf9f33a
Content-type:text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
this is a test message.
--7425195ade9d89bc7492cf520bf9f33a
Content-Type: application/pdf; name="test.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="test.pdf"
JVBERi0xLjMKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29k
ZT4+CnN0cmVhbQp4nE2PT0vEMBDFadVdO4p/v8AcUyFjMmma5CqIIF5cctt6WnFBqLD1+4Np1nY3
c3lvfm+GyQ4VaUY11iQ2PTyuHG5/Ibdx9fIvhi3swJMZX24c602PTzENegwUbNAO4xcoCsG5xuWE
.
... the rest of the file
.
MDAwMDA2MDYgMDAwMDAgbiAKMDAwMDAwMDcwNyAwMDAwMCBuIAowMDAwMDAxMDY4IDAwMDAwIG4g
CjAwMDAwMDA2NDcgMDAwMDAgbiAKMDAwMDAwMDY3NyAwMDAwMCBuIAowMDAwMDAxMjg2IDAwMDAw
IG4gCjAwMDAwMDA5MzIgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSAxNCAvUm9vdCAxIDAgUiAv
SW5mbyAyIDAgUgovSUQgWzxEMURDN0E2OUUzN0QzNjI1MDUyMEFFMjU0MTMxNTQwQz48RDFEQzdB
NjlFMzdEMzYyNTA1MjBBRTI1NDEzMTU0MEM+XQo+PgpzdGFydHhyZWYKNDY5MwolJUVPRgo=
--7425195ade9d89bc7492cf520bf9f33a--
$header ends without a line break
I use the code below to send a message with an attachment as well as html and text message parts. I remember fighting with it a long time to get it right, but unfortunately don't remember which parts were my problems. Maybe looking at it will help you out. I've changed some irrelevant variables and hopefully made it easier to read. Feel free to ask if something is weird or unclear and I'll try to explain.
public function sendEmail($htmlString)
{
$random_hash = md5(date('r', time()));
$message = "--mixed-$random_hash\n";
$message .= 'Content-Type: multipart/alternative; boundary="alt-' . $random_hash . '"' . "\n\n";
$message .= 'MIME-Version: 1.0' . "\n";
$message .= '--alt-' . $random_hash . "\n";
$message .= 'Content-Type: text/plain; charset="iso-8859-1"' . "\n";
$message .= 'Content-Transfer-Encoding: 7bit' . "\n\n";
// text message
$message .= strip_tags($htmlString) . "\n\n";
$message .= '--alt-' . $random_hash . "\n";
$message .= 'Content-Type: text/html; charset="iso-8859-1"' . "\n";
$message .= 'Content-Transfer-Encoding: 7bit' . "\n\n";
// html message
$message .= $htmlString . "\n\n";
$message .= '--alt-' . $random_hash . '--' . "\n";
// graph image
if($this->selectedGraph != 0)
{
$graphString = $this->getGraph(); // image attachment
$graphString = chunk_split(base64_encode($graphString));
$linkID = 'graph-' . $userInfo['FirmID'] . $random_hash . '-image';
$message .= '--mixed-' . $random_hash . "\n";
$message .= 'MIME-Version: 1.0' . "\n";
$message .= 'Content-Transfer-Encoding: base64' . "\n";
$message .= 'Content-ID: ' . $linkID . "\n";
$message .= 'Content-Type: image/gif; name="graph.gif"' . "\n";
$message .= 'Content-Disposition: attachment' . "\n\n";
$message .= $graphString;
$message .= '--mixed-' . $random_hash . '--' . "\n";
}
else
{
$message .= '--mixed-' . $random_hash . '--' . "\n";
}
$headers = 'From: ' . $this->from. "\r\nReply-To: " . $this->replyto;
$headers .= "\r\nContent-Type: multipart/related; boundary=\"mixed-" . $random_hash . "\"\r\nMIME-Version: 1.0";
$flags = '-f ' . BOUNCED_EMAIL_ADDRESS;
return mail($userInfo['Email'], $this->subject, $message, $headers, $flags);
}
These things happen when building mime mails from scratch. There are a couple of php modules you can use to generate cool and compatible mime messages. Mail_Mime should do the trick.

Categories