Index: contrib/z-push/backend/imap.php
===================================================================
--- contrib/z-push/backend/imap.php	(revision 4219)
+++ contrib/z-push/backend/imap.php	(revision 4613)
@@ -91,194 +91,343 @@
 	 * the new message as any other new message in a folder.
 	 */
-	function SendMail($rfc822, $forward = false, $reply = false, $parent = false) {
-		debugLog("IMAP-SendMail: " . $rfc822 . "for: $forward   reply: $reply   parent: $parent" );
-
-		$mobj = new Mail_mimeDecode($rfc822);
-		$message = $mobj->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $rfc822, 'crlf' => "\n", 'charset' => 'utf-8'));
-
-		$toaddr = $ccaddr = $bccaddr = "";
-		if(isset($message->headers["to"]))
-		$toaddr = $this->parseAddr(Mail_RFC822::parseAddressList($message->headers["to"]));
-		if(isset($message->headers["cc"]))
-		$ccaddr = $this->parseAddr(Mail_RFC822::parseAddressList($message->headers["cc"]));
-		if(isset($message->headers["bcc"]))
-		$bccaddr = $this->parseAddr(Mail_RFC822::parseAddressList($message->headers["bcc"]));
-
-		// save some headers when forwarding mails (content type & transfer-encoding)
-		$headers = "";
-		$forward_h_ct = "";
-		$forward_h_cte = "";
-
-		$use_orgbody = false;
-
-		// clean up the transmitted headers
-		// remove default headers because we are using imap_mail
-		$changedfrom = false;
-		$returnPathSet = false;
-		$body_base64 = false;
-		$org_charset = "";
-		foreach($message->headers as $k => $v) {
-			if ($k == "subject" || $k == "to" || $k == "cc" || $k == "bcc")
-			continue;
-
-			if ($k == "content-type") {
-				// save the original content-type header for the body part when forwarding
-				if ($forward) {
-					$forward_h_ct = $v;
-					continue;
-				}
-
-				// set charset always to utf-8
-				$org_charset = $v;
-				$v = preg_replace("/charset=([A-Za-z0-9-\"']+)/", "charset=\"utf-8\"", $v);
-			}
-
-			if ($k == "content-transfer-encoding") {
-				// if the content was base64 encoded, encode the body again when sending
-				if (trim($v) == "base64") $body_base64 = true;
-
-				// save the original encoding header for the body part when forwarding
-				if ($forward) {
-					$forward_h_cte = $v;
-					continue;
-				}
-			}
-
-			// if the message is a multipart message, then we should use the sent body
-			if (!$forward && $k == "content-type" && preg_match("/multipart/i", $v)) {
-				$use_orgbody = true;
-			}
-
-			// check if "from"-header is set
-			if ($k == "from" && ! trim($v) && IMAP_DEFAULTFROM) {
-				$changedfrom = true;
-				if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
-				else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
-				else $v = $this->_username . IMAP_DEFAULTFROM;
-			}
-
-			// check if "Return-Path"-header is set
-			if ($k == "return-path") {
-				$returnPathSet = true;
-				if (! trim($v) && IMAP_DEFAULTFROM) {
-					if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
-					else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
-					else $v = $this->_username . IMAP_DEFAULTFROM;
-				}
-			}
-
-			// all other headers stay
-			if ($headers) $headers .= "\n";
-			$headers .= ucfirst($k) . ": ". $v;
-		}
-
-		// set "From" header if not set on the device
-		if(IMAP_DEFAULTFROM && !$changedfrom){
-			if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
-			else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
-			else $v = $this->_username . IMAP_DEFAULTFROM;
-			if ($headers) $headers .= "\n";
-			$headers .= 'From: '.$v;
-		}
-
-		// set "Return-Path" header if not set on the device
-		if(IMAP_DEFAULTFROM && !$returnPathSet){
-			if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
-			else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
-			else $v = $this->_username . IMAP_DEFAULTFROM;
-			if ($headers) $headers .= "\n";
-			$headers .= 'Return-Path: '.$v;
-		}
-
-		// if this is a multipart message with a boundary, we must use the original body
-		if ($use_orgbody) {
-			list(,$body) = $mobj->_splitBodyHeader($rfc822);
-		}
-		else
-		$body = $this->getBody($message);
-
-		// reply
-		if (isset($reply) && isset($parent) &&  $reply && $parent) {
-			$this->imap_reopenFolder($parent);
-			// receive entire mail (header + body) to decode body correctly
-			$origmail = @imap_fetchheader($this->_mbox, $reply, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $reply, FT_PEEK | FT_UID);
-			$mobj2 = new Mail_mimeDecode($origmail);
-			// receive only body
-			$body .= $this->getBody($mobj2->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $origmail, 'crlf' => "\n", 'charset' => 'utf-8')));
-			// unset mimedecoder & origmail - free memory
-			unset($mobj2);
-			unset($origmail);
-		}
-
-		// encode the body to base64 if it was sent originally in base64 by the pda
-		// the encoded body is included in the forward
-		if ($body_base64) $body = base64_encode($body);
-
-
-		// forward
-		if (isset($forward) && isset($parent) && $forward && $parent) {
-			$this->imap_reopenFolder($parent);
-			// receive entire mail (header + body)
-			$origmail = @imap_fetchheader($this->_mbox, $forward, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $forward, FT_PEEK | FT_UID);
-
-			// build a new mime message, forward entire old mail as file
-			list($aheader, $body) = $this->mail_attach("forwarded_message.eml",strlen($origmail),$origmail, $body, $forward_h_ct, $forward_h_cte);
-
-			// unset origmail - free memory
-			unset($origmail);
-
-			// add boundary headers
-			$headers .= "\n" . $aheader;
-		}
-
-		//advanced debugging
-		//debugLog("IMAP-SendMail: parsed message: ". print_r($message,1));
-		//debugLog("IMAP-SendMail: headers: $headers");
-		//debugLog("IMAP-SendMail: subject: {$message->headers["subject"]}");
-		//debugLog("IMAP-SendMail: body: $body");
-
-		$send =  @imap_mail ( $toaddr, $message->headers["subject"], $body, $headers, $ccaddr, $bccaddr);
-
-		// email sent?
-		if (!$send) {
-			debugLog("The email could not be sent. Last-IMAP-error: ". imap_last_error());
-		}
-
-		// add message to the sent folder
-		// build complete headers
-		$cheaders  = "To: " . $toaddr. "\n";
-		$cheaders .= "Subject: " . $message->headers["subject"] . "\n";
-		$cheaders .= "Cc: " . $ccaddr . "\n";
-		$cheaders .= $headers;
-
-		$asf = false;
-		if ($this->_sentID) {
-			$asf = $this->addSentMessage($this->_sentID, $cheaders, $body);
-		}
-		else if (IMAP_SENTFOLDER) {
-			$asf = $this->addSentMessage(IMAP_SENTFOLDER, $cheaders, $body);
-			debugLog("IMAP-SendMail: Outgoing mail saved in configured 'Sent' folder '".IMAP_SENTFOLDER."': ". (($asf)?"success":"failed"));
-		}
-		// No Sent folder set, try defaults
-		else {
-			debugLog("IMAP-SendMail: No Sent mailbox set");
-			if($this->addSentMessage("INBOX.Sent", $cheaders, $body)) {
-				debugLog("IMAP-SendMail: Outgoing mail saved in 'INBOX.Sent'");
-				$asf = true;
-			}
-			else if ($this->addSentMessage("Sent", $cheaders, $body)) {
-				debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent'");
-				$asf = true;
-			}
-			else if ($this->addSentMessage("Sent Items", $cheaders, $body)) {
-				debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent Items'");
-				$asf = true;
-			}
-		}
-
-		// unset mimedecoder - free memory
-		unset($mobj);
-		return ($send && $asf);
-	}
+    function SendMail($rfc822, $forward = false, $reply = false, $parent = false) {
+        debugLog("IMAP-SendMail: for: $forward   reply: $reply   parent: $parent  RFC822:  \n". $rfc822 );
+
+        $mobj = new Mail_mimeDecode($rfc822);
+        $message = $mobj->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
+        
+        $Mail_RFC822 = new Mail_RFC822();
+        $toaddr = $ccaddr = $bccaddr = "";
+        if(isset($message->headers["to"]))
+            $toaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["to"]));
+        if(isset($message->headers["cc"]))
+            $ccaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["cc"]));
+        if(isset($message->headers["bcc"]))
+            $bccaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["bcc"]));
+
+        // save some headers when forwarding mails (content type & transfer-encoding)
+        $headers = "";
+        $forward_h_ct = "";
+        $forward_h_cte = "";
+        $envelopefrom = "";
+
+        $use_orgbody = false;
+        
+        // clean up the transmitted headers
+        // remove default headers because we are using imap_mail
+        $changedfrom = false;
+        $returnPathSet = false;
+        $body_base64 = false;
+        $org_charset = "";
+        $org_boundary = false;
+        $multipartmixed = false;
+        foreach($message->headers as $k => $v) {
+            if ($k == "subject" || $k == "to" || $k == "cc" || $k == "bcc")
+                continue;
+
+            if ($k == "content-type") {
+                // if the message is a multipart message, then we should use the sent body
+                if (preg_match("/multipart/i", $v)) {
+                    $use_orgbody = true;
+                    $org_boundary = $message->ctype_parameters["boundary"];
+                }
+
+                // save the original content-type header for the body part when forwarding
+                if ($forward && !$use_orgbody) {
+                    $forward_h_ct = $v;
+                    continue;
+                }
+
+                // set charset always to utf-8
+                $org_charset = $v;
+                $v = preg_replace("/charset=([A-Za-z0-9-\"']+)/", "charset=\"utf-8\"", $v);
+            }
+
+            if ($k == "content-transfer-encoding") {
+                // if the content was base64 encoded, encode the body again when sending
+                if (trim($v) == "base64") $body_base64 = true;
+
+                // save the original encoding header for the body part when forwarding
+                if ($forward) {
+                    $forward_h_cte = $v;
+                    continue;
+                }
+            }
+
+            // check if "from"-header is set, do nothing if it's set
+            // else set it to IMAP_DEFAULTFROM
+            if ($k == "from") {
+                if (trim($v)) {
+                    $changedfrom = true;
+                } elseif (! trim($v) && IMAP_DEFAULTFROM) {
+                    $changedfrom = true;
+                    if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+                    else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+                    else $v = $this->_username . IMAP_DEFAULTFROM;
+                    $envelopefrom = "-f$v";
+                }
+            }
+
+            // check if "Return-Path"-header is set
+            if ($k == "return-path") {
+                $returnPathSet = true;
+                if (! trim($v) && IMAP_DEFAULTFROM) {
+                    if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+                    else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+                    else $v = $this->_username . IMAP_DEFAULTFROM;
+                }
+            }
+
+            // all other headers stay
+            if ($headers) $headers .= "\n";
+            $headers .= ucfirst($k) . ": ". $v;
+        }
+
+        // set "From" header if not set on the device
+        if(IMAP_DEFAULTFROM && !$changedfrom){
+            if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+            else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+            else $v = $this->_username . IMAP_DEFAULTFROM;
+            if ($headers) $headers .= "\n";
+            $headers .= 'From: '.$v;
+            $envelopefrom = "-f$v";
+        }
+
+        // set "Return-Path" header if not set on the device
+        if(IMAP_DEFAULTFROM && !$returnPathSet){
+            if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
+            else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
+            else $v = $this->_username . IMAP_DEFAULTFROM;
+            if ($headers) $headers .= "\n";
+            $headers .= 'Return-Path: '.$v;
+        }
+
+        // if this is a multipart message with a boundary, we must use the original body
+        if ($use_orgbody) {
+            list(,$body) = $mobj->_splitBodyHeader($rfc822);
+            $repl_body = $this->getBody($message);
+        }
+        else
+            $body = $this->getBody($message);
+
+        // reply
+        if ($reply && $parent) {
+            $this->imap_reopenFolder($parent);
+            // receive entire mail (header + body) to decode body correctly
+            $origmail = @imap_fetchheader($this->_mbox, $reply, FT_UID) . @imap_body($this->_mbox, $reply, FT_PEEK | FT_UID);
+            $mobj2 = new Mail_mimeDecode($origmail);
+            // receive only body
+            $body .= $this->getBody($mobj2->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8')));
+            // unset mimedecoder & origmail - free memory
+            unset($mobj2);
+            unset($origmail);
+        }
+
+        // encode the body to base64 if it was sent originally in base64 by the pda
+        // contrib - chunk base64 encoded body
+        if ($body_base64 && !$forward) $body = chunk_split(base64_encode($body));
+
+
+        // forward
+        if ($forward && $parent) {
+            $this->imap_reopenFolder($parent);
+            // receive entire mail (header + body)
+            $origmail = @imap_fetchheader($this->_mbox, $forward, FT_UID) . @imap_body($this->_mbox, $forward, FT_PEEK | FT_UID);
+
+            //if (!defined('IMAP_INLINE_FORWARD') || IMAP_INLINE_FORWARD === false) {
+            if (defined('IMAP_INLINE_FORWARD') && IMAP_INLINE_FORWARD === false) {
+                // contrib - chunk base64 encoded body
+                if ($body_base64) $body = chunk_split(base64_encode($body));
+                //use original boundary if it's set
+                $boundary = ($org_boundary) ? $org_boundary : false;
+                // build a new mime message, forward entire old mail as file
+                list($aheader, $body) = $this->mail_attach("forwarded_message.eml",strlen($origmail),$origmail, $body, $forward_h_ct, $forward_h_cte,$boundary);
+                // add boundary headers
+                $headers .= "\n" . $aheader;
+
+            }
+            else {
+                $mobj2 = new Mail_mimeDecode($origmail);
+                $mess2 = $mobj2->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
+
+                if (!$use_orgbody)
+                    $nbody = $body;
+                else
+                    $nbody = $repl_body;
+
+                $nbody .= "\r\n\r\n";
+                $nbody .= "-----Original Message-----\r\n";
+                if(isset($mess2->headers['from']))
+                    $nbody .= "From: " . $mess2->headers['from'] . "\r\n";
+                if(isset($mess2->headers['to']) && strlen($mess2->headers['to']) > 0)
+                    $nbody .= "To: " . $mess2->headers['to'] . "\r\n";
+                if(isset($mess2->headers['cc']) && strlen($mess2->headers['cc']) > 0)
+                    $nbody .= "Cc: " . $mess2->headers['cc'] . "\r\n";
+                if(isset($mess2->headers['date']))
+                    $nbody .= "Sent: " . $mess2->headers['date'] . "\r\n";
+                if(isset($mess2->headers['subject']))
+                    $nbody .= "Subject: " . $mess2->headers['subject'] . "\r\n";
+                $nbody .= "\r\n";
+                $nbody .= $this->getBody($mess2);
+
+                if ($body_base64) {
+                    // contrib - chunk base64 encoded body
+                    $nbody = chunk_split(base64_encode($nbody));
+                    if ($use_orgbody)
+                    // contrib - chunk base64 encoded body
+                        $repl_body = chunk_split(base64_encode($repl_body));
+                }
+
+                if ($use_orgbody) {
+                    debugLog("-------------------");
+                    debugLog("old:\n'$repl_body'\nnew:\n'$nbody'\nund der body:\n'$body'");
+                    //$body is quoted-printable encoded while $repl_body and $nbody are plain text,
+                    //so we need to decode $body in order replace to take place
+                    $body = str_replace($repl_body, $nbody, quoted_printable_decode($body));
+                }
+                else
+                    $body = $nbody;
+
+
+                if(isset($mess2->parts)) {
+                    $attached = false;
+
+                    if ($org_boundary) {
+                        $att_boundary = $org_boundary;
+                        // cut end boundary from body
+                        $body = substr($body, 0, strrpos($body, "--$att_boundary--"));
+                    }
+                    else {
+                        $att_boundary = strtoupper(md5(uniqid(time())));
+                        // add boundary headers
+                        $headers .= "\n" . "Content-Type: multipart/mixed; boundary=$att_boundary";
+                        $multipartmixed = true;
+                    }
+
+                    foreach($mess2->parts as $part) {
+                        if(isset($part->disposition) && ($part->disposition == "attachment" || $part->disposition == "inline")) {
+
+                            if(isset($part->d_parameters['filename']))
+                                $attname = $part->d_parameters['filename'];
+                            else if(isset($part->ctype_parameters['name']))
+                                $attname = $part->ctype_parameters['name'];
+                            else if(isset($part->headers['content-description']))
+                                $attname = $part->headers['content-description'];
+                            else $attname = "unknown attachment";
+
+                            // ignore html content
+                            if ($part->ctype_primary == "text" && $part->ctype_secondary == "html") {
+                                continue;
+                            }
+                            //
+                            if ($use_orgbody || $attached) {
+                                $body .= $this->enc_attach_file($att_boundary, $attname, strlen($part->body),$part->body, $part->ctype_primary ."/". $part->ctype_secondary);
+                            }
+                            // first attachment
+                            else {
+                                $encmail = $body;
+                                $attached = true;
+                                $body = $this->enc_multipart($att_boundary, $body, $forward_h_ct, $forward_h_cte);
+                                $body .= $this->enc_attach_file($att_boundary, $attname, strlen($part->body),$part->body, $part->ctype_primary ."/". $part->ctype_secondary);
+                            }
+                        }
+                    }
+                    if ($multipartmixed) {
+                        //this happens if a multipart/alternative message is forwarded
+                        //then it's a multipart/mixed message which consists of:
+                        //1. text/plain part which was written on the mobile
+                        //2. multipart/alternative part which is the original message
+                        //$body = "This is a message with multiple parts in MIME format.\n--".
+                        //        $att_boundary.
+                        //        "\nContent-Type: $forward_h_ct\nContent-Transfer-Encoding: $forward_h_cte\n\n".
+                        //        (($body_base64) ? chunk_split(base64_encode($message->body)) : rtrim($message->body)).
+                        //        "\n--".$att_boundary.
+                        //        "\nContent-Type: {$mess2->headers['content-type']}\n\n".
+                        //        @imap_body($this->_mbox, $forward, FT_PEEK | FT_UID)."\n\n";
+                        $body = "\n--".
+                                $att_boundary.
+                                "\nContent-Type: $forward_h_ct\nContent-Transfer-Encoding: $forward_h_cte\n\n".
+                                $body;
+                    }
+
+                    $body .= "--$att_boundary--\n\n";
+                }
+
+                unset($mobj2);
+            }
+
+            // unset origmail - free memory
+            unset($origmail);
+
+        }
+
+        // remove carriage-returns from body
+        $body = str_replace("\r\n", "\n", $body);
+
+        if (!$multipartmixed) {
+            if (!empty($forward_h_ct)) $headers .= "\nContent-Type: $forward_h_ct";
+            if (!empty($forward_h_cte)) $headers .= "\nContent-Transfer-Encoding: $forward_h_cte";
+        }
+        //advanced debugging
+        debugLog("IMAP-SendMail: parsed message: ". print_r($message,1));
+        debugLog("IMAP-SendMail: headers: $headers");
+        debugLog("IMAP-SendMail: subject: {$message->headers["subject"]}");
+        debugLog("IMAP-SendMail: body: $body");
+
+        if (!defined('IMAP_USE_IMAPMAIL') || IMAP_USE_IMAPMAIL == true) {
+            $send =  @imap_mail ( $toaddr, $message->headers["subject"], $body, $headers, $ccaddr, $bccaddr);
+        }
+        else {
+            if (!empty($ccaddr))  $headers .= "\nCc: $ccaddr";
+            if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
+            $send =  @mail ( $toaddr, $message->headers["subject"], $body, $headers, $envelopefrom );
+        }
+
+        // email sent?
+        if (!$send) {
+            debugLog("The email could not be sent. Last-IMAP-error: ". imap_last_error());
+        }
+
+        // add message to the sent folder
+        // build complete headers
+        $headers .= "\nTo: $toaddr";
+        $headers .= "\nSubject: " . $message->headers["subject"];
+
+        if (!defined('IMAP_USE_IMAPMAIL') || IMAP_USE_IMAPMAIL == true) {
+            if (!empty($ccaddr))  $headers .= "\nCc: $ccaddr";
+            if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
+        }
+        debugLog("IMAP-SendMail: complete headers: $headers");
+
+        $asf = false;
+        if ($this->_sentID) {
+            $asf = $this->addSentMessage($this->_sentID, $headers, $body);
+        }
+        else if (IMAP_SENTFOLDER) {
+            $asf = $this->addSentMessage(IMAP_SENTFOLDER, $headers, $body);
+            debugLog("IMAP-SendMail: Outgoing mail saved in configured 'Sent' folder '".IMAP_SENTFOLDER."': ". (($asf)?"success":"failed"));
+        }
+        // No Sent folder set, try defaults
+        else {
+            debugLog("IMAP-SendMail: No Sent mailbox set");
+            if($this->addSentMessage("INBOX.Sent", $headers, $body)) {
+                debugLog("IMAP-SendMail: Outgoing mail saved in 'INBOX.Sent'");
+                $asf = true;
+            }
+            else if ($this->addSentMessage("Sent", $headers, $body)) {
+                debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent'");
+                $asf = true;
+            }
+            else if ($this->addSentMessage("Sent Items", $headers, $body)) {
+                debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent Items'");
+                $asf = true;
+            }
+        }
+
+        // unset mimedecoder - free memory
+        unset($mobj);
+        return ($send && $asf);
+    }
+	
 
 	/* Should return a wastebasket folder if there is one. This is used when deleting
@@ -920,29 +1069,43 @@
 
 	// build a multipart email, embedding body and one file (for attachments)
-	function mail_attach($filenm,$filesize,$file_cont,$body, $body_ct, $body_cte) {
-
-		$boundary = strtoupper(md5(uniqid(time())));
-
-		$mail_header = "Content-Type: multipart/mixed; boundary=$boundary\n";
-
-		// build main body with the sumitted type & encoding from the pda
-		$mail_body  = "This is a multi-part message in MIME format\n\n";
-		$mail_body .= "--$boundary\n";
-		$mail_body .= "Content-Type:$body_ct\n";
-		$mail_body .= "Content-Transfer-Encoding:$body_cte\n\n";
-		$mail_body .= "$body\n\n";
-
-		$mail_body .= "--$boundary\n";
-		$mail_body .= "Content-Type: text/plain; name=\"$filenm\"\n";
-		$mail_body .= "Content-Transfer-Encoding: base64\n";
-		$mail_body .= "Content-Disposition: attachment; filename=\"$filenm\"\n";
-		$mail_body .= "Content-Description: $filenm\n\n";
-		$mail_body .= base64_encode($file_cont) . "\n\n";
-
-		$mail_body .= "--$boundary--\n\n";
-
-		return array($mail_header, $mail_body);
-	}
-
+   function mail_attach($filenm,$filesize,$file_cont,$body, $body_ct, $body_cte, $boundary = false) {
+        if (!$boundary) $boundary = strtoupper(md5(uniqid(time())));
+
+        //remove the ending boundary because we will add it at the end
+        $body = str_replace("--$boundary--", "", $body);
+
+        $mail_header = "Content-Type: multipart/mixed; boundary=$boundary\n";
+
+        // build main body with the sumitted type & encoding from the pda
+        $mail_body  = $this->enc_multipart($boundary, $body, $body_ct, $body_cte);
+        $mail_body .= $this->enc_attach_file($boundary, $filenm, $filesize, $file_cont);
+
+        $mail_body .= "--$boundary--\n\n";
+        return array($mail_header, $mail_body);
+    }
+
+    function enc_multipart($boundary, $body, $body_ct, $body_cte) {
+//        $mail_body = "This is a multi-part message in MIME format\n\n";   
+//        $mail_body .= "--$boundary\n";
+//        $mail_body .= "Content-Type: $body_ct\n";
+//        $mail_body .= "Content-Transfer-Encoding: $body_cte\n\n";
+        $mail_body = "$body\n\n";
+
+        return $mail_body;
+    }
+    
+    function enc_attach_file($boundary, $filenm, $filesize, $file_cont, $content_type = "") {
+        if (!$content_type) $content_type = "text/plain";
+        $mail_body = "--$boundary\n";
+        $mail_body .= "Content-Type: $content_type; name=\"$filenm\"\n";
+        $mail_body .= "Content-Transfer-Encoding: base64\n";
+        $mail_body .= "Content-Disposition: attachment; filename=\"$filenm\"\n";
+        $mail_body .= "Content-Description: $filenm\n\n";
+        //contrib - chunk base64 encoded attachments
+        $mail_body .= chunk_split(base64_encode($file_cont)) . "\n\n";
+
+        return $mail_body;
+    }
+	
 	// adds a message as seen to a specified folder (used for saving sent mails)
 	function addSentMessage($folderid, $header, $body) {
