Author: Chris Corbyn
Inheritance: extends Swift_Mime_EmbeddedFile
Beispiel #1
0
 public static function sendEmail($receiver, $obj = "Aucun objet", $content = "", $urlFile = "", $nameFile = "")
 {
     global $config;
     global $twig;
     $message = Swift_Message::newInstance();
     $template = $twig->loadTemplate("email_generique.html5.twig");
     $view = $template->render(["objEmail" => $obj, "messageEmail" => $content]);
     $arrMatches = array();
     preg_match_all('/(src=|url\\()"([^"]+\\.(jpe?g|png|gif|bmp|tiff?|swf))"/Ui', $view, $arrMatches);
     foreach (array_unique($arrMatches[2]) as $url) {
         $src = rawurldecode($url);
         // see #3713
         if (!preg_match('@^https?://@', $src) && file_exists(BASE_ROOT . '/' . $src)) {
             $cid = $message->embed(Swift_EmbeddedFile::fromPath(BASE_ROOT . '/' . $src));
             $view = str_replace(array('src="' . $url . '"', 'url("' . $url . '"'), array('src="' . $cid . '"', 'url("' . $cid . '"'), $view);
         }
     }
     $message->setSubject($obj);
     $message->setFrom($config["smtp"]["sender"]);
     $message->setReplyTo($config["smtp"]["replyTo"]);
     $message->setTo($receiver);
     $message->setBody($view, 'text/html');
     if ($urlFile !== "") {
         $message->attach(Swift_Attachment::fromPath($urlFile)->setFilename($nameFile));
     }
     $mailer = self::getMailer();
     $mailer->send($message);
 }
Beispiel #2
0
 /**
  * Create a new EmbeddedFile.
  *
  * Details may be optionally provided to the constructor.
  *
  * @param string|Swift_OutputByteStream $data
  * @param string $filename
  * @param string $contentType
  */
 public function __construct($data = null, $filename = null, $contentType = null)
 {
     parent::__construct($data, $filename, $contentType);
 }
Beispiel #3
0
 /**
  * Embeds an attachment into the message and returns its reference.
  *
  * @param string $data Binary or string
  * @param string $mimetype Mime type of the attachment (e.g. "text/plain", "application/octet-stream", etc.)
  * @param string|null $filename Name of the attached file
  * @return string Content ID for referencing the attachment in the HTML body
  */
 public function embedAttachment($data, $mimetype, $filename)
 {
     $part = \Swift_EmbeddedFile::newInstance($data, $mimetype, $filename);
     return $this->object->embed($part);
 }
Beispiel #4
0
 /**
  * Send the e-mail
  *
  * Friendly name portions (e.g. Admin <*****@*****.**>) are allowed. The
  * method takes an unlimited number of recipient addresses.
  * 
  * @return boolean True if the e-mail was sent successfully
  */
 public function sendTo()
 {
     $arrRecipients = $this->compileRecipients(func_get_args());
     if (empty($arrRecipients)) {
         return false;
     }
     $this->objMessage->setTo($arrRecipients);
     $this->objMessage->setCharset($this->strCharset);
     $this->objMessage->setPriority($this->intPriority);
     // Default subject
     if ($this->strSubject == '') {
         $this->strSubject = 'No subject';
     }
     $this->objMessage->setSubject($this->strSubject);
     // HTML e-mail
     if ($this->strHtml != '') {
         // Embed images
         if ($this->blnEmbedImages) {
             if ($this->strImageDir == '') {
                 $this->strImageDir = TL_ROOT . '/';
             }
             $arrMatches = array();
             preg_match_all('/(src=|url\\()"([^"]+\\.(jpe?g|png|gif|bmp|tiff?|swf))"/Ui', $this->strHtml, $arrMatches);
             $strBase = \Environment::get('base');
             // Check for internal images
             foreach (array_unique($arrMatches[2]) as $url) {
                 // Try to remove the base URL
                 $src = str_replace($strBase, '', $url);
                 $src = rawurldecode($src);
                 // see #3713
                 // Embed the image if the URL is now relative
                 if (!preg_match('@^https?://@', $src) && file_exists($this->strImageDir . $src)) {
                     $cid = $this->objMessage->embed(\Swift_EmbeddedFile::fromPath($this->strImageDir . $src));
                     $this->strHtml = str_replace(array('src="' . $url . '"', 'url("' . $url . '"'), array('src="' . $cid . '"', 'url("' . $cid . '"'), $this->strHtml);
                 }
             }
         }
         $this->objMessage->setBody($this->strHtml, 'text/html');
     }
     // Text content
     if ($this->strText != '') {
         if ($this->strHtml != '') {
             $this->objMessage->addPart($this->strText, 'text/plain');
         } else {
             $this->objMessage->setBody($this->strText, 'text/plain');
         }
     }
     // Add the administrator e-mail as default sender
     if ($this->strSender == '') {
         list($this->strSenderName, $this->strSender) = $this->splitFriendlyName($GLOBALS['TL_CONFIG']['adminEmail']);
     }
     // Sender
     if ($this->strSenderName != '') {
         $this->objMessage->setFrom(array($this->strSender => $this->strSenderName));
     } else {
         $this->objMessage->setFrom($this->strSender);
     }
     // Send e-mail
     $intSent = self::$objMailer->send($this->objMessage, $this->arrFailures);
     // Log failures
     if (!empty($this->arrFailures)) {
         log_message('E-mail address rejected: ' . implode(', ', $this->arrFailures), $this->strLogFile);
     }
     // Return if no e-mails have been sent
     if ($intSent < 1) {
         return false;
     }
     $arrCc = $this->objMessage->getCc();
     $arrBcc = $this->objMessage->getBcc();
     // Add a log entry
     $strMessage = 'An e-mail has been sent to ' . implode(', ', array_keys($this->objMessage->getTo()));
     if (!empty($arrCc)) {
         $strMessage .= ', CC to ' . implode(', ', array_keys($arrCc));
     }
     if (!empty($arrBcc)) {
         $strMessage .= ', BCC to ' . implode(', ', array_keys($arrBcc));
     }
     log_message($strMessage, $this->strLogFile);
     return true;
 }
Beispiel #5
0
 /**
  * @inheritdoc
  */
 public function embedContent($content, array $options = [])
 {
     $embedFile = \Swift_EmbeddedFile::newInstance($content);
     if (!empty($options['fileName'])) {
         $embedFile->setFilename($options['fileName']);
     }
     if (!empty($options['contentType'])) {
         $embedFile->setContentType($options['contentType']);
     }
     return $this->getSwiftMessage()->embed($embedFile);
 }
 protected function _createEmbeddedFile()
 {
     return Swift_EmbeddedFile::newInstance();
 }
Beispiel #7
0
 /**
  * Create a new EmbeddedFile.
  * Details may be optionally provided to the constructor.
  * @param string|Swift_OutputByteStream $data
  * @param string                        $filename
  * @param string                        $contentType
  */
 public function __construct($data = NULL, $filename = NULL, $contentType = NULL)
 {
     parent::__construct($data, $filename, $contentType);
 }
 public function createEmbeddedFile($filePath)
 {
     return \Swift_EmbeddedFile::fromPath($filePath);
 }
Beispiel #9
0
    /**
     * handleEmailFormInput
     * 
     * This method can be used in Models and Controllers. It puts the email body
     * and inline (image) attachments from the client in the message, which can
     * then be used for storage in the database or sending emails.
     * 
     * @param Array $params Must contain elements: body (string) and
     * 
     * inlineAttachments (string).
     */
    public function handleEmailFormInput($params)
    {
        if (!empty($params['subject'])) {
            $this->setSubject($params['subject']);
        }
        if (!empty($params['to'])) {
            $to = new EmailRecipients($params['to']);
            foreach ($to->getAddresses() as $email => $personal) {
                $this->addTo($email, $personal);
            }
        }
        if (!empty($params['cc'])) {
            $cc = new EmailRecipients($params['cc']);
            foreach ($cc->getAddresses() as $email => $personal) {
                $this->addCc($email, $personal);
            }
        }
        if (!empty($params['bcc'])) {
            $bcc = new EmailRecipients($params['bcc']);
            foreach ($bcc->getAddresses() as $email => $personal) {
                $this->addBcc($email, $personal);
            }
        }
        if (isset($params['alias_id'])) {
            $alias = \GO\Email\Model\Alias::model()->findByPk($params['alias_id']);
            $this->setFrom($alias->email, $alias->name);
            if (!empty($params['notification'])) {
                $this->setReadReceiptTo(array($alias->email => $alias->name));
            }
        }
        if (isset($params['priority'])) {
            $this->setPriority($params['priority']);
        }
        if (isset($params['in_reply_to'])) {
            $headers = $this->getHeaders();
            $headers->addTextHeader('In-Reply-To', $params['in_reply_to']);
            $headers->addTextHeader('References', $params['in_reply_to']);
        }
        if ($params['content_type'] == 'html') {
            $params['htmlbody'] = $this->_embedPastedImages($params['htmlbody']);
            //inlineAttachments is an array(array('url'=>'',tmp_file=>'relative/path/');
            if (!empty($params['inlineAttachments'])) {
                $inlineAttachments = json_decode($params['inlineAttachments']);
                /* inline attachments must of course exist as a file, and also be used in
                 * the message body
                 */
                if (count($inlineAttachments)) {
                    foreach ($inlineAttachments as $ia) {
                        //$tmpFile = new \GO\Base\Fs\File(\GO::config()->tmpdir.$ia['tmp_file']);
                        if (empty($ia->tmp_file)) {
                            continue;
                            // Continue to the next inline attachment for processing.
                            //throw new Exception("No temp file for inline attachment ".$ia->name);
                        }
                        $path = empty($ia->from_file_storage) ? \GO::config()->tmpdir . $ia->tmp_file : \GO::config()->file_storage_path . $ia->tmp_file;
                        $tmpFile = new \GO\Base\Fs\File($path);
                        if ($tmpFile->exists()) {
                            //Different browsers reformat URL's to absolute or relative. So a pattern match on the filename.
                            //$filename = rawurlencode($tmpFile->name());
                            $result = preg_match('/="([^"]*' . preg_quote($ia->token) . '[^"]*)"/', $params['htmlbody'], $matches);
                            if ($result) {
                                $img = \Swift_EmbeddedFile::fromPath($tmpFile->path());
                                $img->setContentType($tmpFile->mimeType());
                                $contentId = $this->embed($img);
                                //$tmpFile->delete();
                                $params['htmlbody'] = \GO\Base\Util\String::replaceOnce($matches[1], $contentId, $params['htmlbody']);
                            } else {
                                //this may happen when an inline image was attached but deleted in the editor afterwards.
                                //
                                //throw new \Exception("Error: inline attachment could not be found in text: ".$ia->token);
                            }
                        } else {
                            throw new \Exception("Error: inline attachment missing on server: " . $tmpFile->stripTempPath() . ".<br /><br />The temporary files folder is cleared on each login. Did you relogin?");
                        }
                    }
                }
            }
            $params['htmlbody'] = $this->_fixRelativeUrls($params['htmlbody']);
            $htmlTop = '<html>
<head>
<style type="text/css">
body,p,td,div,span{
	' . \GO::config()->html_editor_font . '
};
body p{
	margin:0px;
}
</style>
</head>
<body>';
            $htmlBottom = '</body></html>';
            $this->setHtmlAlternateBody($htmlTop . $params['htmlbody'] . $htmlBottom);
        } else {
            $this->setBody($params['plainbody'], 'text/plain');
        }
        if (!empty($params['attachments'])) {
            $attachments = json_decode($params['attachments']);
            foreach ($attachments as $att) {
                $path = empty($att->from_file_storage) ? \GO::config()->tmpdir . $att->tmp_file : \GO::config()->file_storage_path . $att->tmp_file;
                $tmpFile = new \GO\Base\Fs\File($path);
                if ($tmpFile->exists()) {
                    $file = \Swift_Attachment::fromPath($tmpFile->path());
                    $file->setContentType($tmpFile->mimeType());
                    $file->setFilename($att->fileName);
                    $this->attach($file);
                    //$tmpFile->delete();
                } else {
                    throw new \Exception("Error: attachment missing on server: " . $tmpFile->stripTempPath() . ".<br /><br />The temporary files folder is cleared on each login. Did you relogin?");
                }
            }
        }
    }
Beispiel #10
0
 /**
  * Generates a CID for a data by which the data can be embedded into the body of a message.
  *
  * The same CID can be used to embed a data in more than one place.
  *
  * For example, an image for which a CID was generated and put into `$cid` variable can be embedded into a message
  * with HTML type of body by `<img src="' . $cid . '" alt="Title" />`.
  *
  * @param  data $data The data to be embedded.
  * @param  string $filename The filename to be associated with the embedded data.
  * @param  string $type The MIME type of the data's contents.
  *
  * @return CUStringObject The embeddable CID of the data.
  */
 public function embeddableCidForData($data, $filename, $type)
 {
     assert('is_cstring($data) && is_cstring($filename) && is_cstring($type)', vs(isset($this), get_defined_vars()));
     assert('isset($this->m_swiftMessage)', vs(isset($this), get_defined_vars()));
     $data = _from_oop_tp($data);
     $embeddedFile = Swift_EmbeddedFile::newInstance($data, $filename, $type);
     return $this->m_swiftMessage->embed($embeddedFile);
 }
Beispiel #11
0
 /**
  * Set the html content of the mail which will be used as template.
  * The content will be edited to include images as attachements if needed.
  *
  * @param   string      The html content of the mail
  * @return   void
  */
 private function setHtml($src)
 {
     // Convert external files resources to attached files or correct their links
     $replace_regs = array('/ src="([^"]+)"/', '/ background="([^"]+)"/');
     // Attach images if option is set
     if ($this->extConf['attach_images']) {
         foreach ($replace_regs as $replace_reg) {
             preg_match_all($replace_reg, $src, $urls);
             foreach ($urls[1] as $i => $url) {
                 // Mark places for embedded files and keep the embed files to be replaced
                 $swiftEmbeddedMarker = '###_#_SWIFT_EMBEDDED_MARKER_' . count($this->attachmentsEmbedded) . '_#_###';
                 $this->attachmentsEmbedded[$swiftEmbeddedMarker] = Swift_EmbeddedFile::fromPath($url);
                 $src = str_replace($urls[0][$i], str_replace($url, $swiftEmbeddedMarker, $urls[0][$i]), $src);
             }
         }
     }
     // Detect what markers we need to substitute later on
     preg_match_all('/###(\\w+)###/', $src, $fields);
     preg_match_all('|"http://(\\w+)"|', $src, $fieldsLinks);
     $this->htmlMarkers = array_merge($fields[1], $fieldsLinks[1]);
     // Any advanced IF fields we need to sustitute later on
     $this->htmlAdvancedMarkers = array();
     preg_match_all('/###:IF: (\\w+) ###/U', $src, $fields);
     foreach ($fields[1] as $field) {
         $this->htmlAdvancedMarkers[] = $field;
     }
     $this->html_tpl = $src;
     $this->html = $src;
 }
Beispiel #12
0
 /**
  * Process the message before sending
  * 
  * @return void
  */
 public function procAssembleMessage()
 {
     // Add all attachments
     foreach ($this->attachments as $original_filename => $filename) {
         $attachment = \Swift_Attachment::fromPath($original_filename);
         $attachment->setFilename($filename);
         $this->message->attach($attachment);
     }
     // Add all CID attachments
     foreach ($this->cidAttachments as $cid => $original_filename) {
         $embedded = \Swift_EmbeddedFile::fromPath($original_filename);
         $newcid = $this->message->embed($embedded);
         $this->content = str_replace(array("cid:{$cid}", $cid), $newcid, $this->content);
     }
     // Set content type
     $content_type = $this->content_type === 'html' ? 'text/html' : 'text/plain';
     $this->message->setBody($this->content, $content_type);
 }
Beispiel #13
0
 /**
  * Embed a file from dynamic content
  *
  * @param string $data
  * @param string $fileName
  * @param string $contentType
  * @return string An identifier of the embed file
  */
 function embedData($data, $fileName = null, $contentType = null)
 {
     $file = Swift_EmbeddedFile::newInstance($data, $fileName, $contentType);
     return $this->embed($file);
 }
Beispiel #14
0
 /**
  * Embed a file.
  *
  * @param string $local_filename
  * @param string $cid (optional)
  * @return string|false
  */
 public function embed($local_filename, $cid = null)
 {
     if (!Storage::exists($local_filename)) {
         return false;
     }
     $embedded = \Swift_EmbeddedFile::fromPath($local_filename);
     if ($cid !== null) {
         $embedded->setId(preg_replace('/^cid:/i', '', $cid));
     }
     $result = $this->message->embed($embedded);
     if ($result) {
         $this->attachments[] = (object) array('type' => 'embed', 'local_filename' => $local_filename, 'display_filename' => null, 'cid' => $result);
         return $result;
     } else {
         return false;
     }
 }
 protected function updateFilePath($file, Swift_Message $message, $templateName)
 {
     $id = str_replace('dmFile-', '', $file->id);
     if (!$id) {
         $id = $file->getAttribute('data-dm-file-id');
     }
     if (is_numeric($id)) {
         $mediaRecord = dmDb::table('dmMedia')->findOneByIdWithFolder($id);
         if ($mediaRecord) {
             $embed = false;
             $embedExtensions = array_map('trim', explode(',', dmConfig::get('mail_template_embed_file_types', 'doc,docx,xls,xlsx,ppt,pptx,pdf,mdb')));
             foreach ($embedExtensions as $ext) {
                 if (dmString::endsWith($file->href, '.' . $ext, false)) {
                     $embed = true;
                     break;
                 }
             }
             if (dmConfig::get('mail_template_embed_local_files_as_attachments', true) && $embed) {
                 try {
                     $file->href = $message->embed(Swift_EmbeddedFile::fromPath(dmOs::join(sfConfig::get('sf_web_dir'), $mediaRecord->getWebPath())));
                 } catch (Exception $e) {
                     $this->logError($templateName, 'local', 'file', $file->href);
                     $file->href = '';
                 }
             } else {
                 if (file_exists(dmOs::join(sfConfig::get('sf_web_dir'), $link = $mediaRecord->getWebPath()))) {
                     $file->href = $this->basePath . '/' . $mediaRecord->getWebPath();
                 } else {
                     $this->logError($templateName, 'local', 'file', $file->href);
                     $file->href = '';
                 }
             }
             return $file;
         }
     }
     if (dmString::startsWith($file->href, sfConfig::get('sf_root_dir')) || dmString::startsWith($file->href, $this->basePath)) {
         return $this->updateLocalFilePath($file, $message, $templateName);
     } else {
         return $this->updateRemoteFilePath($file, $message, $templateName);
     }
 }
Beispiel #16
-2
 /**
  * Send the e-mail
  *
  * Friendly name portions (e.g. Admin <*****@*****.**>) are allowed. The
  * method takes an unlimited number of recipient addresses.
  *
  * @return boolean True if the e-mail was sent successfully
  */
 public function sendTo()
 {
     $arrRecipients = $this->compileRecipients(func_get_args());
     if (empty($arrRecipients)) {
         return false;
     }
     $this->objMessage->setTo($arrRecipients);
     $this->objMessage->setCharset($this->strCharset);
     $this->objMessage->setPriority($this->intPriority);
     // Default subject
     if ($this->strSubject == '') {
         $this->strSubject = 'No subject';
     }
     $this->objMessage->setSubject($this->strSubject);
     // HTML e-mail
     if ($this->strHtml != '') {
         // Embed images
         if ($this->blnEmbedImages) {
             if ($this->strImageDir == '') {
                 $this->strImageDir = TL_ROOT . '/';
             }
             $arrCid = array();
             $arrMatches = array();
             $strBase = \Environment::get('base');
             // Thanks to @ofriedrich and @aschempp (see #4562)
             preg_match_all('/<[a-z][a-z0-9]*\\b[^>]*((src=|background=|url\\()["\']??)(.+\\.(jpe?g|png|gif|bmp|tiff?|swf))(["\' ]??(\\)??))[^>]*>/Ui', $this->strHtml, $arrMatches);
             // Check for internal images
             if (!empty($arrMatches) && isset($arrMatches[0])) {
                 for ($i = 0, $c = count($arrMatches[0]); $i < $c; $i++) {
                     $url = $arrMatches[3][$i];
                     // Try to remove the base URL
                     $src = str_replace($strBase, '', $url);
                     $src = rawurldecode($src);
                     // see #3713
                     // Embed the image if the URL is now relative
                     if (!preg_match('@^https?://@', $src) && file_exists($this->strImageDir . $src)) {
                         if (!isset($arrCid[$src])) {
                             $arrCid[$src] = $this->objMessage->embed(\Swift_EmbeddedFile::fromPath($this->strImageDir . $src));
                         }
                         $this->strHtml = str_replace($arrMatches[1][$i] . $arrMatches[3][$i] . $arrMatches[5][$i], $arrMatches[1][$i] . $arrCid[$src] . $arrMatches[5][$i], $this->strHtml);
                     }
                 }
             }
         }
         $this->objMessage->setBody($this->strHtml, 'text/html');
     }
     // Text content
     if ($this->strText != '') {
         if ($this->strHtml != '') {
             $this->objMessage->addPart($this->strText, 'text/plain');
         } else {
             $this->objMessage->setBody($this->strText, 'text/plain');
         }
     }
     // Add the administrator e-mail as default sender
     if ($this->strSender == '') {
         list($this->strSenderName, $this->strSender) = \String::splitFriendlyEmail(\Config::get('adminEmail'));
     }
     // Sender
     if ($this->strSenderName != '') {
         $this->objMessage->setFrom(array($this->strSender => $this->strSenderName));
     } else {
         $this->objMessage->setFrom($this->strSender);
     }
     // Set the return path (see #5004)
     $this->objMessage->setReturnPath($this->strSender);
     // Send e-mail
     $intSent = self::$objMailer->send($this->objMessage, $this->arrFailures);
     // Log failures
     if (!empty($this->arrFailures)) {
         log_message('E-mail address rejected: ' . implode(', ', $this->arrFailures), $this->strLogFile);
     }
     // Return if no e-mails have been sent
     if ($intSent < 1) {
         return false;
     }
     $arrCc = $this->objMessage->getCc();
     $arrBcc = $this->objMessage->getBcc();
     // Add a log entry
     $strMessage = 'An e-mail has been sent to ' . implode(', ', array_keys($this->objMessage->getTo()));
     if (!empty($arrCc)) {
         $strMessage .= ', CC to ' . implode(', ', array_keys($arrCc));
     }
     if (!empty($arrBcc)) {
         $strMessage .= ', BCC to ' . implode(', ', array_keys($arrBcc));
     }
     log_message($strMessage, $this->strLogFile);
     return true;
 }