function sendMail(ezcMail $mail) { $separator = "/"; $mail->appendExcludeHeaders(array('to', 'subject')); $headers = rtrim($mail->generateHeaders()); // rtrim removes the linebreak at the end, mail doesn't want it. if (count($mail->to) + count($mail->cc) + count($mail->bcc) < 1) { throw new ezcMailTransportException('No recipient addresses found in message header.'); } $additionalParameters = ""; if (isset($mail->returnPath)) { $additionalParameters = "-f{$mail->returnPath->email}"; } $sys = eZSys::instance(); $fname = time() . '-' . rand() . '.mail'; $qdir = eZSys::siteDir() . eZSys::varDirectory() . $separator . 'mailq'; $data = $headers . ezcMailTools::lineBreak(); $data .= ezcMailTools::lineBreak(); $data .= $mail->generateBody(); $data = preg_replace('/(\\r\\n|\\r|\\n)/', "\r\n", $data); $success = eZFile::create($fname, $qdir, $data); if ($success === false) { throw new ezcMailTransportException('The email could not be sent by sendmail'); } }
public static function send($to, $subject, $body, $options = array()) { $siteINI = eZINI::instance('site.ini'); $i18nINI = eZINI::instance('i18n.ini'); $transport = $siteINI->variable('MailSettings', 'Transport'); $charset = $i18nINI->variable('CharacterSettings', 'Charset'); $emailSender = $siteINI->variable('MailSettings', 'EmailSender'); if (!$emailSender) { $emailSender = $siteINI->variable('MailSettings', 'AdminEmail'); } if ($transport == 'SMTP') { $mailTransport = new ezcMailSmtpTransport($siteINI->variable('MailSettings', 'TransportServer'), $siteINI->variable('MailSettings', 'TransportUser'), $siteINI->variable('MailSettings', 'TransportPassword'), $siteINI->variable('MailSettings', 'TransportPort')); } else { eZDebug::writeError('Only SMTP Transport supported', 'jajNewsletterSubscription::sendConfirmationMail'); throw new Exception('Only SMTP Transport supported'); } $mail = new ezcMailComposer(); $mail->charset = $charset; $mail->subjectCharset = $charset; $mail->subject = $subject; $mail->htmlText = $body; $mail->from = ezcMailTools::parseEmailAddress($emailSender, $charset); $mail->addTo(new ezcMailAddress($to, '', $charset)); $mail->build(); $mailTransport->send($mail); }
public function testFoldAny76LongWord() { $reference = "Thisisalongwordthatismorethan76characterslong.Let'sseehowthisishandledbyourlittlefolder That was the first space."; ezcMailHeaderFolder::setLimit(ezcMailHeaderFolder::SOFT_LIMIT); $folded = ezcMailHeaderFolder::foldAny($reference); $exploded = explode(ezcMailTools::lineBreak(), $folded); $this->assertEquals(2, count($exploded)); $this->assertEquals(87, strlen($exploded[0])); $this->assertEquals(26, strlen($exploded[1])); }
/** * Override of original {@link ezcMail::generateHeaders()}. * Allows headers customization * * @return string The mail headers */ public function generateHeaders() { // Workaround for encoded email addresses. // When encoded, email addresses (at least the name param) have more characters // By default, line length is set to 76 characters, after what a new line is created with $lineBreak. // This operation is done during encoding via iconv (see ezcMailTools::composeEmailAddress()). // Problem is that this operation is done a 2nd time in ezcMailPart::generateHeaders(). // Following code ensures that there is no double $lineBreak introduced // by this process because it potentially breaks headers $lineBreak = ezcMailTools::lineBreak(); $headers = str_replace("{$lineBreak}{$lineBreak}", $lineBreak, parent::generateHeaders()); return $headers; }
/** * Sends the mail $mail using the PHP mail method. * * Note that a message may not arrive at the destination even though * it was accepted for delivery. * * @throws ezcMailTransportException * if the mail was not accepted for delivery by the MTA. * @param ezcMail $mail */ public function send(ezcMail $mail) { $mail->appendExcludeHeaders(array('to', 'subject')); $headers = rtrim($mail->generateHeaders()); // rtrim removes the linebreak at the end, mail doesn't want it. if (count($mail->to) + count($mail->cc) + count($mail->bcc) < 1) { throw new ezcMailTransportException('No recipient addresses found in message header.'); } $additionalParameters = ""; if (isset($mail->returnPath)) { $additionalParameters = "-f{$mail->returnPath->email}"; } $success = mail(ezcMailTools::composeEmailAddresses($mail->to), $mail->getHeader('Subject'), $mail->generateBody(), $headers, $additionalParameters); if ($success === false) { throw new ezcMailTransportException('The email could not be sent by sendmail'); } }
/** * Adds $part to the list of parts and returns the Content-ID of the part. * * @param ezcMailPart $part * @return string */ public function addRelatedPart(ezcMailPart $part) { // it doesn't have a Content-ID, we must set one. $contentId = ''; if ($part->getHeader('Content-ID') == '') { if ($part instanceof ezcMailFile) { $part->contentId = ezcMailTools::generateContentId(basename($part->fileName)); } else { $part->setHeader('Content-ID', ezcMailTools::generateContentId('part')); } } $contentId = trim($part->getHeader('Content-ID'), '<>'); // Set the content ID property of the ezcMailFile if one was found if ($part instanceof ezcMailFile) { $part->contentId = $contentId; } if (count($this->parts) > 0) { $this->parts[] = $part; } else { $this->parts[1] = $part; } return $contentId; }
/** * Returns an ezcMailPart based on the HTML provided. * * This method adds local files/images to the mail itself using a * {@link ezcMailMultipartRelated} object. * * @throws ezcBaseFileNotFoundException * if $fileName does not exists. * @throws ezcBaseFilePermissionProblem * if $fileName could not be read. * @return ezcMailPart */ private function generateHtmlPart() { $result = false; if ($this->htmlText != '') { $matches = array(); if ($this->options->automaticImageInclude === true) { // recognize file:// and file:///, pick out the image, add it as a part and then..:) preg_match_all("/<img[\\s\\*\\s]src=[\\'\"]file:\\/\\/([^ >\\'\"]+)/i", $this->htmlText, $matches); // pictures/files can be added multiple times. We only need them once. $matches = array_unique($matches[1]); } $result = new ezcMailText($this->htmlText, $this->charset, $this->encoding); $result->subType = "html"; if (count($matches) > 0) { $htmlPart = $result; // wrap already existing message in an alternative part $result = new ezcMailMultipartRelated($result); // create a filepart and add it to the related part // also store the ID for each part since we need those // when we replace the originals in the HTML message. foreach ($matches as $fileName) { if (is_readable($fileName)) { // @todo waiting for fix of the fileinfo extension // $contents = file_get_contents( $fileName ); $mimeType = null; $contentType = null; if (ezcBaseFeatures::hasExtensionSupport('fileinfo')) { // if fileinfo extension is available $filePart = new ezcMailFile($fileName); } elseif (ezcMailTools::guessContentType($fileName, $contentType, $mimeType)) { // if fileinfo extension is not available try to get content/mime type // from the file extension $filePart = new ezcMailFile($fileName, $contentType, $mimeType); } else { // fallback in case fileinfo is not available and could not get content/mime // type from file extension $filePart = new ezcMailFile($fileName, "application", "octet-stream"); } $cid = $result->addRelatedPart($filePart); // replace the original file reference with a reference to the cid $this->htmlText = str_replace('file://' . $fileName, 'cid:' . $cid, $this->htmlText); } else { if (file_exists($fileName)) { throw new ezcBaseFilePermissionException($fileName, ezcBaseFileException::READ); } else { throw new ezcBaseFileNotFoundException($fileName); } // throw } } // update mail, with replaced URLs $htmlPart->text = $this->htmlText; } } return $result; }
/** * Returns the complete mail part including both the header and the body * as a string. * * @return string */ public function generate() { return $this->generateHeaders() . ezcMailTools::lineBreak() . $this->generateBody(); }
public function testFoldingAddresses() { $this->mail->from = new ezcMailAddress('*****@*****.**'); $addresses = array('*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'); foreach ($addresses as $address) { $this->mail->addBcc(new ezcMailAddress($address)); } $expected = "From: from@ez.no" . ezcMailTools::lineBreak() . "To: " . ezcMailTools::lineBreak() . "Bcc: nospam1@ez.no, nospam2@ez.no, nospam3@ez.no, nospam4@ez.no, nospam5@ez.no," . ezcMailTools::lineBreak() . " nospam6@ez.no, nospam7@ez.no" . ezcMailTools::lineBreak() . "Subject: " . ezcMailTools::lineBreak() . "MIME-Version: 1.0" . ezcMailTools::lineBreak() . "User-Agent: eZ Components"; $return = $this->mail->generate(); // cut away the Date and Message-ID headers as there is no way to predict what they will be $return = join(ezcMailTools::lineBreak(), array_slice(explode(ezcMailTools::lineBreak(), $return), 0, 7)); $this->assertEquals($expected, $return); }
$newFile = tempnam($this->dir, 'mail'); copy($mailPart->fileName, $newFile); // save location and setup ID array $this->cids[$mailPart->contentId] = $this->webDir . '/' . basename($newFile); } // if we find a text part and if the sub-type is HTML (no plain text) // we store that in the classes' htmlText property. if ($mailPart instanceof ezcMailText) { if ($mailPart->subType == 'html') { $this->htmlText = $mailPart->text; } } } } // create the collector class and set the filesystem path, and the webserver's // path to find the attached files (images) in. $collector = new collector(); $collector->dir = "/home/httpd/html/test/ezc"; $collector->webDir = '/test/ezc'; // We use the saveMailPart() method of the $collector object function as a // callback in walkParts(). $context = new ezcMailPartWalkContext(array($collector, 'saveMailPart')); // only call the callback for file and text parts. $context->filter = array('ezcMailFile', 'ezcMailText'); // use walkParts() to iterate over all parts in the first parsed e-mail // message. $mail[0]->walkParts($context, $mail[0]); // display the html text with the content IDs replaced with references to the // file in the webroot. echo ezcMailTools::replaceContentIdRefs($collector->htmlText, $collector->cids);
/** * Returns $text folded to the 998 character limit on any whitespace. * * The algorithm tries to minimize the number of comparisons by searching * backwards from the maximum number of allowed characters on a line. * * @param string $text * @return string */ public static function foldAny($text) { // Don't fold unless we have to. if (strlen($text) <= self::$limit) { return $text; } // go to 998'th char. // search back to whitespace // fold $length = strlen($text); $folded = ""; // find first occurence of whitespace searching backwards $search = 0; $previousFold = 0; while ($search + self::$limit < $length) { // search from the max possible length of the substring $search += self::$limit; while ($text[$search] != " " && $text[$search] != "\t" && $search > $previousFold) { $search--; } if ($search == $previousFold) { // continuous string of more than limit chars. // We will just have to continue searching forwards to the next whitespace instead // This is not confirming to standard.. but what can we do? $search += self::$limit; // back to where we started while ($search < $length && $text[$search] != " " && $text[$search] != "\t") { $search++; } } // lets fold if ($folded === "") { $folded = substr($text, $previousFold, $search - $previousFold); } else { $folded .= ezcMailTools::lineBreak() . substr($text, $previousFold, $search - $previousFold); } $previousFold = $search; } // we need to append the rest if there is any if ($search < $length) { $folded .= ezcMailTools::lineBreak() . substr($text, $search); } return $folded; }
/** * Returns the generated text for a section of the delivery-status part. * * @param ezcMailHeadersHolder $headers * @return string */ private function addHeadersSection(ezcMailHeadersHolder $headers) { $result = ""; foreach ($headers->getCaseSensitiveArray() as $header => $value) { $result .= $header . ": " . $value . ezcMailTools::lineBreak(); } return $result; }
public function testNoDoubleFold() { $composedAddress = ezcMailTools::composeEmailAddress(new ezcMailAddress('*****@*****.**', 'From name ØÆÅ test test test test with a very long name which contains norwegian characters ÆØÅæøÅ', 'utf-8')); $this->assertSame($composedAddress, ezcMailHeaderFolder::foldAny($composedAddress)); }
/** * Returns an ezcMailPart based on the HTML provided. * * This method adds local files/images to the mail itself using a * {@link ezcMailMultipartRelated} object. * * @throws ezcBaseFileNotFoundException * if $fileName does not exists. * @throws ezcBaseFilePermissionProblem * if $fileName could not be read. * @return ezcMailPart */ private function generateHtmlPart() { $result = false; if ($this->htmlText != '') { $matches = array(); if ($this->options->automaticImageInclude === true) { /* 1.7.1 regex is buggy filename are not extract correctly http://issues.ez.no/IssueView.php?Id=16612& preg_match_all( '( <img \\s+[^>]* src\\s*=\\s* (?: (?# Match quoted attribute) ([\'"])file://(?P<quoted>[^>]+)\\1 (?# Match unquoted attribute, which may not contain spaces) | file://(?P<unquoted>[^>\\s]+) ) [^>]* >)ix', $htmlText, $matches ); * */ // CJW Newsletter regex change only find all file://ezroot/ // so it is secure // recognize file://ezroot/ and pick out the image, add it as a part and then..:) preg_match_all("/<img[\\s\\*\\s]src=[\\'\"]file:\\/\\/ezroot\\/([^ >\\'\"]+)/i", $this->htmlText, $matches); // pictures/files can be added multiple times. We only need them once. $matches = array_unique($matches[1]); } $result = new ezcMailText($this->htmlText, $this->charset, $this->encoding); $result->subType = "html"; if (count($matches) > 0) { $htmlPart = $result; // wrap already existing message in an alternative part $result = new ezcMailMultipartRelated($result); // create a filepart and add it to the related part // also store the ID for each part since we need those // when we replace the originals in the HTML message. foreach ($matches as $fileName) { if (is_readable($fileName)) { // @todo waiting for fix of the fileinfo extension // $contents = file_get_contents( $fileName ); $mimeType = null; $contentType = null; if (ezcBaseFeatures::hasExtensionSupport('fileinfo')) { // if fileinfo extension is available $filePart = new ezcMailFile($fileName); } elseif (ezcMailTools::guessContentType($fileName, $contentType, $mimeType)) { // if fileinfo extension is not available try to get content/mime type // from the file extension $filePart = new ezcMailFile($fileName, $contentType, $mimeType); } else { // fallback in case fileinfo is not available and could not get content/mime // type from file extension $filePart = new ezcMailFile($fileName, "application", "octet-stream"); } $cid = $result->addRelatedPart($filePart); // replace the original file reference with a reference to the cid $this->htmlText = str_replace('file://ezroot/' . $fileName, 'cid:' . $cid, $this->htmlText); } else { if (file_exists($fileName)) { throw new ezcBaseFilePermissionException($fileName, ezcBaseFileException::READ); } else { throw new ezcBaseFileNotFoundException($fileName); } // throw } } // update mail, with replaced URLs $htmlPart->text = $this->htmlText; } } return $result; }
/** * Returns the a ezcMailContentDispositionHeader for the parsed $header. * * If $cd is provided this object will be used to fill in the blanks. This function * will not clear out any old values in the object. * * @param string $header * @param ezcMailContentDispositionHeader $cd * @return ezcMailContentDispositionHeader */ public static function parseContentDisposition($header, ezcMailContentDispositionHeader $cd = null) { if ($cd === null) { $cd = new ezcMailContentDispositionHeader(); } $parsedHeader = self::parseHeader($header); $cd->disposition = $parsedHeader[0]; if (isset($parsedHeader[1])) { foreach ($parsedHeader[1] as $paramName => $data) { switch ($paramName) { case 'filename': $cd->fileName = $data['value']; $cd->displayFileName = trim($data['value'], '"'); if (isset($data['charset'])) { $cd->fileNameCharSet = $data['charset']; $cd->displayFileName = ezcMailCharsetConverter::convertToUTF8Iconv($cd->displayFileName, $cd->fileNameCharSet); } else { if (preg_match('@^=\\?[^?]+\\?[QqBb]\\?@', $cd->displayFileName)) { $cd->displayFileName = ezcMailTools::mimeDecode($cd->displayFileName); } } if (isset($data['language'])) { $cd->fileNameLanguage = $data['language']; } break; case 'creation-date': $cd->creationDate = $data['value']; break; case 'modification-date': $cd->modificationDate = $data['value']; break; case 'read-date': $cd->readDate = $data['value']; break; case 'size': $cd->size = $data['value']; break; default: $cd->additionalParameters[$paramName] = $data['value']; if (isset($data['charset'])) { $cd->additionalParametersMetaData[$paramName]['charSet'] = $data['charset']; } if (isset($data['language'])) { $cd->additionalParametersMetaData[$paramName]['language'] = $data['language']; } break; } } } return $cd; }
/** * Returns the contents of the file with the correct encoding. * * @return string */ public function generateBody() { return chunk_split(base64_encode(file_get_contents($this->fileName)), 76, ezcMailTools::lineBreak()); }
/** * Returns the contents of the file with the correct encoding. * * @return string */ public function generateBody() { return chunk_split(base64_encode($this->contents), 76, ezcMailTools::lineBreak()); }
/** * Returns the contents of the file with the correct encoding. * * The stream might become unusable after this if it doesn't support seek. * * @return string */ public function generateBody() { $contents = stream_get_contents($this->stream); return chunk_split(base64_encode($contents), 76, ezcMailTools::lineBreak()); }
public function testQuotedPrintableEncode() { $reference = "Content-Type: text/plain; charset=iso-8859-1" . ezcMailTools::lineBreak() . "Content-Transfer-Encoding: quoted-printable" . ezcMailTools::lineBreak() . ezcMailTools::lineBreak() . "=E6=F8=E5=0A=F8=E6=E5"; $text = new ezcMailText("זרו\nרזו", "iso-8859-1", ezcMail::QUOTED_PRINTABLE); $this->assertEquals($reference, $text->generate()); }
/** * Returns an ezcMail corresponding to the parsed message. * You can specify an alternate class using the $class parameter, if you * extended ezcMail. * * @param string $class Class to instanciate instead of ezcMail. * @return ezcMail */ public function finish($class = "ezcMail") { $mail = new $class(); $mail->setHeaders($this->headers->getCaseSensitiveArray()); ezcMailPartParser::parsePartHeaders($this->headers, $mail); // from if (isset($this->headers['From'])) { $mail->from = ezcMailTools::parseEmailAddress($this->headers['From']); } // to if (isset($this->headers['To'])) { $mail->to = ezcMailTools::parseEmailAddresses($this->headers['To']); } // cc if (isset($this->headers['Cc'])) { $mail->cc = ezcMailTools::parseEmailAddresses($this->headers['Cc']); } // bcc if (isset($this->headers['Bcc'])) { $mail->bcc = ezcMailTools::parseEmailAddresses($this->headers['Bcc']); } // subject if (isset($this->headers['Subject'])) { $mail->subject = ezcMailTools::mimeDecode($this->headers['Subject']); $mail->subjectCharset = 'utf-8'; } // message ID if (isset($this->headers['Message-Id'])) { $mail->messageID = $this->headers['Message-Id']; } // Return-Path if (isset($this->headers['Return-Path'])) { $mail->returnPath = ezcMailTools::parseEmailAddress($this->headers['Return-Path']); } if ($this->bodyParser !== null) { $mail->body = $this->bodyParser->finish(); } return $mail; }
/** * Sorts message numbers array $messages by the specified $sortCriteria. * * This method supports unique IDs instead of message numbers. See * {@link ezcMailImapTransportOptions} for how to enable unique IDs * referencing. * * $messages is an array of message numbers, for example: * <code> * array( 1, 2, 4 ); * </code> * * $sortCriteria is an email header like: Subject, To, From, Date, Sender. * * The sorting is done with the php function natcasesort(). * * Before calling this method, a connection to the IMAP server must be * established and a user must be authenticated successfully, and a mailbox * must be selected. * * @throws ezcMailTransportException * if a mailbox is not selected * or if the server sent a negative response * or if the array $messages is empty * @param array(int) $messages * @param string $sortCriteria * @param bool $reverse * @return array(string) */ protected function sort($messages, $sortCriteria, $reverse = false) { $uid = $this->options->uidReferencing ? self::UID : self::NO_UID; if ($this->state != self::STATE_SELECTED && $this->state != self::STATE_SELECTED_READONLY) { throw new ezcMailTransportException("Can't call sort() on the IMAP transport when a mailbox is not selected."); } $result = array(); $query = ucfirst(strtolower($sortCriteria)); $messageNumbers = implode(',', $messages); $tag = $this->getNextTag(); $this->connection->sendData("{$tag} {$uid}FETCH {$messageNumbers} (BODY.PEEK[HEADER.FIELDS ({$query})])"); $response = trim($this->connection->getLine()); while (strpos($response, $tag) === false) { if (strpos($response, ' FETCH (') !== false) { if ($this->options->uidReferencing) { preg_match('/^\\* [0-9]+ FETCH \\(UID ([0-9]+)/', $response, $matches); } else { preg_match('/^\\* ([0-9]+) FETCH/', $response, $matches); } $messageNumber = $matches[1]; } if (strpos($response, $query) !== false) { $strippedResponse = trim(trim(str_replace("{$query}: ", '', $response)), '"'); switch ($query) { case 'Date': $strippedResponse = strtotime($strippedResponse); break; case 'Subject': case 'From': case 'Sender': case 'To': $strippedResponse = ezcMailTools::mimeDecode($strippedResponse); break; default: break; } $result[$messageNumber] = $strippedResponse; } // in case the mail doesn't have the $sortCriteria header (like junk mail missing Subject header) if (strpos($response, ')') !== false && !isset($result[$messageNumber])) { $result[$messageNumber] = ''; } $response = trim($this->connection->getLine()); } if ($this->responseType($response) != self::RESPONSE_OK) { throw new ezcMailTransportException("The IMAP server could not sort the messages: {$response}."); } if ($reverse === true) { natcasesort($result); $result = array_reverse($result, true); } else { natcasesort($result); } return $result; }
/** * Sets the correct stream filters for the attachment. * * $line should contain one line of data that should be written to file. * It is used to correctly determine the type of linebreak used in the mail. * * @param string $line */ private function appendStreamFilters($line) { // append the correct decoding filter switch (strtolower($this->headers['Content-Transfer-Encoding'])) { case 'base64': stream_filter_append($this->fp, 'convert.base64-decode'); break; case 'quoted-printable': // fetch the type of linebreak preg_match("/(\r\n|\r|\n)\$/", $line, $matches); $lb = count($matches) > 0 ? $matches[0] : ezcMailTools::lineBreak(); $param = array('line-break-chars' => $lb); stream_filter_append($this->fp, 'convert.quoted-printable-decode', STREAM_FILTER_WRITE, $param); break; case '7bit': case '8bit': // do nothing here, file is already just binary break; default: // 7bit default break; } }
/** * Returns the generated text body of this part as a string. * * @return string */ public function generateBody() { switch ($this->encoding) { case ezcMail::BASE64: // leaves a \r\n to much at the end, but since it is base64 it will decode // properly so we just leave it return chunk_split(base64_encode($this->text), 76, ezcMailTools::lineBreak()); break; case ezcMail::QUOTED_PRINTABLE: $text = preg_replace_callback('/[^\\x21-\\x3C\\x3E-\\x7E\\x09\\x20]/', function ($matches) { return sprintf("=%02X", ord($matches[0])); }, $this->text); preg_match_all('/.{1,73}([^=]{0,2})?/', $text, $match); $text = implode('=' . ezcMailTools::lineBreak(), $match[0]); return $text; break; default: return preg_replace("/\r\n|\r|\n/", ezcMailTools::lineBreak(), $this->text); } }
/** * Test for issue #14487: Enable ezcMailComposer to specify encoding for text and html parts */ public function testMailTextAndHtmlSetBase64Encoding() { $this->mail->from = new ezcMailAddress('*****@*****.**', 'Frederik Holljen'); $this->mail->addTo(new ezcMailAddress('*****@*****.**', 'Frederik Holljen')); $this->mail->subject = "Alternative HTML/Text message."; $this->mail->plainText = "Plain text message. Your client should show the HTML message if it supports HTML mail."; $this->mail->htmlText = "<html><i><b>HTML message. Your client should show this if it supports HTML.</b></i></html>"; $this->mail->encoding = ezcMail::BASE64; $this->mail->build(); $message = $this->mail->generate(); $this->parseAndCheckParts($message, array('ezcMailText', 'ezcMailText')); $expected = "PGh0bWw+PGk+PGI+SFRNTCBtZXNzYWdlLiBZb3VyIGNsaWVudCBzaG91bGQgc2hvdyB0aGlzIGlm" . ezcMailTools::lineBreak() . "IGl0IHN1cHBvcnRzIEhUTUwuPC9iPjwvaT48L2h0bWw+"; // test if the $expected BASE64 encoded string is found somewhere in the generated mail (at position 759 usually) $this->assertGreaterThan(500, strpos($message, $expected)); }
/** * Returns the generated headers for the mail. * * This method is called automatically when the mail message is built. * You can re-implement this method in subclasses if you wish to set * different mail headers than ezcMail. * * @return string */ public function generateHeaders() { // set our headers first. if ($this->from !== null) { $this->setHeader("From", ezcMailTools::composeEmailAddress($this->from)); } if ($this->to !== null) { $this->setHeader("To", ezcMailTools::composeEmailAddresses($this->to)); } if (count($this->cc)) { $this->setHeader("Cc", ezcMailTools::composeEmailAddresses($this->cc)); } if (count($this->bcc)) { $this->setHeader("Bcc", ezcMailTools::composeEmailAddresses($this->bcc)); } $this->setHeader('Subject', $this->subject, $this->subjectCharset); $this->setHeader('MIME-Version', '1.0'); $this->setHeader('User-Agent', 'eZ Components'); $this->setHeader('Date', date('r')); $idhost = $this->from != null && $this->from->email != '' ? $this->from->email : 'localhost'; if (is_null($this->messageId)) { $this->setHeader('Message-Id', '<' . ezcMailTools::generateMessageId($idhost) . '>'); } else { $this->setHeader('Message-Id', $this->messageID); } // if we have a body part, include the headers of the body if (is_subclass_of($this->body, "ezcMailPart")) { return parent::generateHeaders() . $this->body->generateHeaders(); } return parent::generateHeaders(); }
public function testResolveCids() { $parser = new ezcMailParser(); $set = new ezcMailFileSet(array(dirname(__FILE__) . '/parser/data/various/test-html-inline-images')); $mail = $parser->parseMail($set); $relatedParts = $mail[0]->body->getParts(); $alternativeParts = $relatedParts[0]->getParts(); $html = $alternativeParts[1]->getMainPart(); $convertArray = array('consoletools-table.png@1421450' => 'foo', 'consoletools-table.png@1421452' => 'bar'); $htmlBody = ezcMailTools::replaceContentIdRefs($html->text, $convertArray); $expected = <<<EOFE <html> Here is the HTML version of your mail with an image: <img src='foo'/> with an image: <img src='cid:consoletools-table.png@1421451'/> </html> EOFE; self::assertSame($expected, $htmlBody); }
/** * Returns the generated body for all multipart types. * * @return string */ public function generateBody() { $data = $this->noMimeMessage . ezcMailTools::lineBreak(); foreach ($this->parts as $part) { $data .= ezcMailTools::lineBreak() . '--' . $this->boundary . ezcMailTools::lineBreak(); $data .= $part->generate(); } $data .= ezcMailTools::lineBreak() . '--' . $this->boundary . '--'; return $data; }
public function testMockSetHeaderWithEncodingNoCharsetReturnDefault() { $part = $this->getMock('ezcMailPart', array('setHeaderCharset', 'generateBody'), array()); $part->expects($this->any())->method('setHeaderCharset')->will($this->returnValue(false)); $part->expects($this->any())->method('generateBody')->will($this->returnValue(false)); $part->setHeader("X-Related-Movie", 'James Bond - Шпион, который меня любил', 'iso-8859-5'); $this->assertEquals('James Bond - Шпион, который меня любил', $part->getHeader('X-Related-Movie')); $expected = "X-Related-Movie: James Bond - Шпион, который меня любил" . ezcMailTools::lineBreak(); $this->assertEquals($expected, $part->generateHeaders()); }
/** * Returns a new mail object that is a reply to the current object. * * The new mail will have the correct to, cc, bcc and reference headers set. * It will not have any body set. * * By default the reply will only be sent to the sender of the original mail. * If $type is set to REPLY_ALL, all the original recipients will be included * in the reply. * * Use $subjectPrefix to set the prefix to the subject of the mail. The default * is to prefix with 'Re: '. * * @param ezcMail $mail * @param ezcMailAddress $from * @param int $type REPLY_SENDER or REPLY_ALL * @param string $subjectPrefix * @param string $mailClass * @return ezcMail */ public static function replyToMail(ezcMail $mail, ezcMailAddress $from, $type = self::REPLY_SENDER, $subjectPrefix = "Re: ", $mailClass = "ezcMail") { $reply = new $mailClass(); $reply->from = $from; // To = Reply-To if set if ($mail->getHeader('Reply-To') != '') { $reply->to = ezcMailTools::parseEmailAddresses($mail->getHeader('Reply-To')); } else { $reply->to = array($mail->from); } if ($type == self::REPLY_ALL) { // Cc = Cc + To - your own address $cc = array(); foreach ($mail->to as $address) { if ($address->email != $from->email) { $cc[] = $address; } } foreach ($mail->cc as $address) { if ($address->email != $from->email) { $cc[] = $address; } } $reply->cc = $cc; } $reply->subject = $subjectPrefix . $mail->subject; if ($mail->getHeader('Message-Id')) { // In-Reply-To = Message-Id $reply->setHeader('In-Reply-To', $mail->getHeader('Message-ID')); // References = References . Message-Id if ($mail->getHeader('References') != '') { $reply->setHeader('References', $mail->getHeader('References') . ' ' . $mail->getHeader('Message-ID')); } else { $reply->setHeader('References', $mail->getHeader('Message-ID')); } } else { $reply->setHeader('References', $mail->getHeader('References')); } return $reply; }
} $customDataText2 = ''; if (isset($item['custom_data_text_2'])) { $customDataText2 = $item['custom_data_text_2']; } $customDataText3 = ''; if (isset($item['custom_data_text_3'])) { $customDataText3 = $item['custom_data_text_3']; } $customDataText4 = ''; if (isset($item['custom_data_text_4'])) { $customDataText4 = $item['custom_data_text_4']; } $eZUserId = false; $newsletterUserId = 0; $emailOk = ezcMailTools::validateEmailAddress($email); $subscriptionObject = null; $createNewUser = 0; // 0 - no, 1 - yes, 2 - updated $createNewSubscription = 0; // store status from existing objects and new stati after import/update $existingUserStatus = -1; $existingSubscriptionStatus = -1; $newUserStatus = -1; $newSubscriptionStatus = -1; $userIsBlacklistedOrRemoved = false; if (!$emailOk) { $emailOk = 0; } else { $emailOk = 1; if ($csvImportHasPrio == false) {