public function __construct(ConfigObject $config = null) { $this->message = new \Swift_Message(); if ($config) { $this->message->setCharset($config->get('CharacterSet', 'utf-8')); $this->message->setMaxLineLength($config->get('MaxLineLength', 78)); if ($config->get('Priority', false)) { $this->message->setPriority($config->get('Priority', 3)); } } }
/** * Set the charset of the charset to use in the message * @param string The charset (e.g. utf-8, iso-8859-1 etc) * @return boolean */ public function setCharset($charset) { try { $this->message->setCharset($charset); return true; } catch (Swift_Message_MimeException $e) { $this->setError("Unable to set the message charset:<br />" . $e->getMessage()); return false; } }
/** * Set the charset of the charset to use in the message * @param string The charset (e.g. utf-8, iso-8859-1 etc) * @return boolean */ function setCharset($charset) { Swift_Errors::expect($e, "Swift_Message_MimeException"); $this->message->setCharset($charset); if ($e) { $this->setError("Unable to set the message charset:<br />" . $e->getMessage()); return false; } Swift_Errors::clear("Swift_Message_MimeException"); return true; }
/** * Create message from config params * * @param $subject * @param $message * @param array $placeholders email message placeholders in body * */ public function createMessage($subject, $message, array $placeholders = []) { // get mail configurations $config = $this->getConfig(); // add smtp exception plugin to resolve SMTP errors $this->mailer->registerPlugin(new MailSMTPException()); // add decorator plugin to resolve messages placeholders $this->mailer->registerPlugin(new \Swift_Plugins_DecoratorPlugin($placeholders)); // prepare message to transport $this->message = \Swift_Message::newInstance(); $this->message->setFrom([$config['fromEmail'] => $config['fromName']]); $this->message->setSubject($subject); $this->message->setBody($message, 'text/html'); $this->message->setCharset('UTF-8'); $this->message->setReadReceiptTo($config['fromEmail']); $this->message->setPriority(1); }
/** * Prepare the email message. */ public function processEmail() { $this->count = 1; $mail = new Swift_Message(); $mail->setContentType('text/plain'); $mail->setCharset('utf-8'); if ($this->getOption('use_complete_template', true)) { $mail->setBody(sprintf(<<<EOF ------ %s - %s ------ %s ------ EOF , $this->options['name'], $this->options['email'], $this->options['message'])); } else { $mail->setBody($this->options['message']); } $mail->setSender(array(sfPlop::get('sf_plop_messaging_from_email') => sfPlop::get('sf_plop_messaging_from_name'))); $mail->setFrom(array($this->options['email'] => $this->options['name'])); if ($this->getOption('copy')) { $mail->setCc(array($this->options['email'] => $this->options['name'])); $this->count++; } if (is_integer($this->getOption('receiver'))) { $receiver = sfGuardUserProfilePeer::retrieveByPK($this->getOption('receiver')); if ($receiver) { $mail->setTo(array($receiver->getEmail() => $receiver->getFullName())); } else { $mail->setTo(array(sfPlop::get('sf_plop_messaging_to_email') => sfPlop::get('sf_plop_messaging_to_name'))); } } else { $mail->setTo(array(sfPlop::get('sf_plop_messaging_to_email') => sfPlop::get('sf_plop_messaging_to_name'))); } if ($this->getOption('subject')) { $mail->setSubject($this->getOption('subject')); } else { $mail->setSubject(sfPlop::get('sf_plop_messaging_subject')); } $this->mail = $mail; }
/** * Send mail. * * @param array $from From address array('*****@*****.**' => 'John Doe'). * @param array $to To address '*****@*****.**' or array('*****@*****.**' => 'A name'). * @param string $subject Subject. * @param string $body Content body. * @param array $contentType Content type for body, default 'text/plain'. * @param array $cc CC to, array('*****@*****.**', '*****@*****.**' => 'A name'). * @param array $bcc BCC to, array('*****@*****.**', '*****@*****.**' => 'A name'). * @param array $replyTo Reply to, array('*****@*****.**', '*****@*****.**' => 'A name'). * @param mixed $altBody Alternate body. * @param string $altBodyContentType Alternate content type default 'text/html'. * @param array $header Associative array of headers array('header1' => 'value1', 'header2' => 'value2'). * @param array &$failedRecipients Array. * @param string $charset Null means leave at default. * @param array $attachments Array of files. * * @return integet */ function send(array $from, array $to, $subject, $body, $contentType = 'text/plain', array $cc = null, array $bcc = null, array $replyTo = null, $altBody = null, $altBodyContentType = 'text/html', array $header = array(), &$failedRecipients = array(), $charset = null, array $attachments = array()) { $message = new Swift_Message($subject, $body, $contentType); $message->setTo($to); $message->setFrom($from); if ($attachments) { foreach ($attachments as $attachment) { $message->attach(Swift_Attachment::fromPath($attachment)); } } if ($cc) { $message->setCc($cc); } if ($bcc) { $message->setBcc($bcc); } if ($replyTo) { $message->setReplyTo($replyTo); } if ($charset) { $message->setCharset($charset); } if ($altBody) { $message->addPart($altBody, $altBodyContentType); } if ($headers) { $headers = $message->getHeaders(); foreach ($headers as $key => $value) { $headers->addTextHeader($key, $value); } } if ($this->serviceManager['swiftmailer.preferences.sendmethod'] == 'normal') { return $this->mailer->send($message, $failedRecipients); } else { if ($this->serviceManager['swiftmailer.preferences.sendmethod'] == 'single_recipient') { return $this->mailer->sendBatch($message, $failedRecipients); } } }
/** * Initializes the message instance. * * @param \Swift_Message $object Swift message object * @param string $charset Default charset of the message */ public function __construct(\Swift_Message $object, $charset) { $object->setCharset($charset); $this->object = $object; }
private function sendMail($customer_email, $body, $subject, $id_shop) { $method = (int) Configuration::get('PS_MAIL_METHOD'); if ($method == 3) { return true; } try { if ($method == 2) { $server = Configuration::get('PS_MAIL_SERVER'); $port = Configuration::get('PS_MAIL_SMTP_PORT'); $encryption = Configuration::get('PS_MAIL_SMTP_ENCRYPTION'); $user = Configuration::get('PS_MAIL_USER'); $password = Configuration::get('PS_MAIL_PASSWD'); if (empty($server) || empty($port)) { return 205; } $connection = new Swift_Connection_SMTP($server, $port, $encryption == 'ssl' ? Swift_Connection_SMTP::ENC_SSL : ($encryption == 'tls' ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF)); $connection->setTimeout(4); if (!$connection) { return 206; } if (!empty($user)) { $connection->setUsername($user); } if (!empty($password)) { $connection->setPassword($password); } } else { $connection = new Swift_Connection_NativeMail(); if (!$connection) { return 207; } } $swift = new Swift($connection, Configuration::get('PS_MAIL_DOMAIN', null, null, $id_shop)); $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject); $message->setCharset('utf-8'); $message->headers->setEncoding('Q'); if (Context::getContext()->link instanceof Link === false) { Context::getContext()->link = new Link(); } $message->attach(new Swift_Message_Part($body, 'text/html', '8bit', 'utf-8')); /* Send mail */ $swift->send($message, $customer_email, new Swift_Address(Configuration::get('PS_SHOP_EMAIL'), Configuration::get('PS_SHOP_NAME', null, null, $id_shop))); $swift->disconnect(); return true; } catch (Swift_Exception $e) { return 208; } }
/** * FUNCTION: _sendMail * * Proccesses all headers and attachments ready for sending. * * @access private */ function _sendMail() { $message = new Swift_Message($this->subject); if (empty($this->sendto) and (empty($this->body) and empty($this->htmlbody))) { vlibMimeMailError::raiseError('VM_ERROR_CANNOT_SEND', FATAL); } // Attachments for ($index = 0; $index < sizeof($this->attachments); $index++) { $message->attach(new Swift_Message_Attachment(new Swift_File($this->attachments[$index]), $this->attachments[$index], $this->mimetypes[$index])); } // ReplyTo if exists if (!empty($this->replyToEmail)) { $message->setReplyTo(new Swift_Address($this->replyToEmail, $this->replyToName)); } // attach body if exist if (!empty($this->body)) { if (empty($this->htmlbody) and sizeof($this->attachments) == 0) { $message->setData($this->body); Swift_ClassLoader::load('Swift_Message_Encoder'); if (Swift_Message_Encoder::instance()->isUTF8($this->body)) { $message->setCharset('utf-8'); } else { $message->setCharset('iso-8859-1'); } } else { $message->attach(new Swift_Message_Part($this->body, 'text/plain')); } } // attach HTML body if exist if (!empty($this->htmlbody)) { $message->attach(new Swift_Message_Part($this->htmlbody, 'text/html')); } return $this->swift->send($message, $this->swift_recipients, new Swift_Address($this->fromEmail, $this->fromName)); }
$entityManager = EntityManager::create($dbParams, $annotationMetadataConfiguration, $eventManager); $helperSet = ConsoleRunner::createHelperSet($entityManager); $logger = new Logger("hipay"); $logFilePath = $parameters['log.file.path'] ?: DEFAULT_LOG_PATH; $logger->pushHandler(new StreamHandler($logFilePath)); $swiftTransport = new Swift_SmtpTransport($parameters['mail.host'], $parameters['mail.port'], $parameters['mail.security']); if (isset($parameters['mail.username']) && isset($parameters['mail.password'])) { $swiftTransport->setUsername($parameters['mail.username']); $swiftTransport->setPassword($parameters['mail.password']); } $mailer = new Swift_Mailer($swiftTransport); $messageTemplate = new Swift_Message(); $messageTemplate->setSubject($parameters['mail.subject']); $messageTemplate->setTo($parameters['mail.to']); $messageTemplate->setFrom($parameters['mail.from']); $messageTemplate->setCharset('utf-8'); $logger->pushHandler(new SwiftMailerHandler($mailer, $messageTemplate, Logger::CRITICAL)); $logger->pushProcessor(new PsrLogMessageProcessor()); /** @var ValidatorInterface $validator */ $validator = Validation::createValidatorBuilder()->enableAnnotationMapping()->getValidator(); $miraklConfiguration = new MiraklConfiguration($parameters); $hipayConfiguration = new HiPayConfiguration($parameters); $eventDispatcher = new EventDispatcher(); $eventDispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) use($parameters, $logger) { $command = $event->getCommand(); if ($parameters['debug'] && $command instanceof AbstractCommand) { $style = new Style($event->getInput(), $event->getOutput()); $command->addDebugLogger($logger, $style); } }); $documentRepository = $entityManager->getRepository('HiPay\\Wallet\\Mirakl\\Integration\\Entity\\Document');
/** * Send the mail * @param string|array $to - mail reciver, can be also as array('*****@*****.**' => 'John Doe') * @param enum(html|text) $format - format of letter (html or text) * @return boolean */ public function send($to, $format = 'text') { //include_once LIBPATH rad_mailtemplate::setCurrentItem($this); $o = rad_rsmarty::getSmartyObject(); if ($this->getVars()) { foreach ($this->getVars() as $key => $value) { $o->assign($key, $value); } } if (!is_file(MAILTEMPLATESPATH . $this->getTemplateName())) { throw new rad_exception('File "' . MAILTEMPLATESPATH . $this->getTemplateName() . '" not found!'); } $o->fetch(MAILTEMPLATESPATH . $this->getTemplateName()); $o->clearAllAssign(); if (empty($this->_blocks[$format])) { throw new rad_exception('Format "' . $format . '" is not declared in file: "' . MAILTEMPLATESPATH . $this->getTemplateName() . '"'); } if (!empty($this->_mailer)) { $this->_mailer->setSubject($this->_blocks[$format]['subject']); if (!empty($this->_blocks[$format]['Cc'])) { $this->_mailer->setCc($this->_blocks[$format]['Cc']); } if (!empty($this->_blocks[$format]['Bcc'])) { $this->_mailer->setBcc($this->_blocks[$format]['Bcc']); } if (!empty($this->_blocks[$format]['headers'])) { $headers = rad_mailtemplate::parseHeader($this->_blocks[$format]['headers']); if (!empty($headers)) { foreach ($headers as $headerName => $headerValue) { switch (strtolower($headerName)) { case 'x-priority': $this->_mailer->setPriority((int) $headerValue); break; default: $this->_mailer->getHeaders()->addTextHeader($headerName, $headerValue); break; } } } } if (!empty($this->_blocks[$format]['body'])) { $this->_mailer->setBody($this->_blocks[$format]['body'], $format == 'text' ? 'text/plain' : 'text/html'); } if (!empty($this->_blocks[$format]['from'])) { $from = explode("\n", str_replace("\r", '', $this->_blocks[$format]['from'])); if (count($from)) { foreach ($from as $fromString) { $fromItem = explode('<', $fromString); if (count($fromItem) > 1) { $fromName = trim($fromItem[0]); $fromEmail = trim(str_replace('>', '', $fromItem[1])); } else { $fromName = trim($fromItem[0]); $fromEmail = trim($fromItem[0]); } $this->_mailer->setFrom(array($fromEmail => $fromName)); $this->_mailer->setReturnPath($fromEmail); } } } if (!empty($this->_blocks[$format]['transport'])) { $transport = explode("\n", str_replace("\r", '', $this->_blocks[$format]['transport'])); if (!empty($transport)) { $transportParams = array(); foreach ($transport as $transportKey => $transportString) { $transportString = trim($transportString); if (!empty($transportString)) { $transportItem = explode(':', $transportString); if (count($transportItem) > 1) { $transportItemKey = trim($transportItem[0]); unset($transportItem[0]); $transportItemValue = trim(implode(':', $transportItem)); $transportParams[$transportItemKey] = $transportItemValue; } } } } if (empty($transportParams['type'])) { throw new rad_exception('Error in mailtemplate "' . $this->getTemplateName() . '" at transport block: type of the transport required!'); } switch (strtolower($transportParams['type'])) { case 'smtp': if (empty($transportParams['host']) or empty($transportParams['port']) or empty($transportParams['user']) or !isset($transportParams['password'])) { throw new rad_exception('Error in mailtemplate "' . $this->getTemplateName() . '" at transport block: Not enouph actual params!'); } $this->_transportInstance = Swift_SmtpTransport::newInstance($transportParams['host'], $transportParams['port'])->setUsername($transportParams['user'])->setPassword($transportParams['password']); if (!empty($transportParams['security'])) { $this->_transportInstance->setEncryption($transportParams['security']); } break; case 'mail': $this->_transportInstance = Swift_MailTransport::newInstance(); break; default: throw new rad_exception('Error in mailtemplate "' . $this->getTemplateName() . '" Unknown transport type "' . $transportParams['type'] . '"!'); break; } //switch } $this->_mailer->setTo($to); $this->_mailer->setCharset('utf-8'); if (!$this->_transportInstance) { $this->_transportInstance = Swift_MailTransport::newInstance(); } return rad_mailtemplate::getMailer($this->_transportInstance)->send($this->_mailer); } else { $headers = 'MIME-Version: 1.0' . PHP_EOL; $headers .= 'Content-Transfer-Encoding: base64' . PHP_EOL; $headers .= 'From: ' . $this->_blocks[$format]['from'] . PHP_EOL; switch ($format) { case 'text': $headers = 'Content-Type: text/plain; charset=utf-8' . PHP_EOL; break; case 'html': $headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL; break; default: throw new rad_exception('Unknown format: "' . $format . '"'); break; } if (!empty($this->_blocks[$format]['Cc'])) { $headers .= 'Cc: ' . $this->_blocks[$format]['Cc'] . PHP_EOL; } if (!empty($this->_blocks[$format]['Bcc'])) { $headers .= 'Bcc: ' . $this->_blocks[$format]['Bcc'] . PHP_EOL; } if (!empty($this->_blocks[$format]['headers'])) { $headers .= $this->_blocks[$format]['headers']; } if (is_array($to)) { $toString = ''; foreach ($to as $toEmail => $toName) { $toString .= $toName . ' <' . $toEmail . '>,'; } $to = substr($toString, 0, strlen($toString) - 1); } return mail($to, $this->_blocks[$format]['subject'], chunk_split(base64_encode($this->_blocks[$format]['body'])), $headers); } }
/** * 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; }
/** * Send Email * * @param int $id_lang Language of the email (to translate the template) * @param string $template Template: the name of template not be a var but a string ! * @param string $subject * @param string $template_vars * @param string $to * @param string $to_name * @param string $from * @param string $from_name * @param array $file_attachment Array with three parameters (content, mime and name). You can use an array of array to attach multiple files * @param bool $modeSMTP * @param string $template_path * @param bool $die * @param string $bcc Bcc recipient */ public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null, $bcc = null) { $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_TYPE'), null, null, $id_shop); // Returns immediatly if emails are deactivated if ($configuration['PS_MAIL_METHOD'] == 3) { return true; } $theme_path = _PS_THEME_DIR_; // Get the path of theme by id_shop if exist if (is_numeric($id_shop) && $id_shop) { $shop = new Shop((int) $id_shop); $theme_name = $shop->getTheme(); if (_THEME_NAME_ != $theme_name) { $theme_path = _PS_ROOT_DIR_ . '/themes/' . $theme_name . '/'; } } if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION'])) { $configuration['PS_MAIL_SMTP_ENCRYPTION'] = 'off'; } if (!isset($configuration['PS_MAIL_SMTP_PORT'])) { $configuration['PS_MAIL_SMTP_PORT'] = 'default'; } // Sending an e-mail can be of vital importance for the merchant, when his password is lost for example, so we must not die but do our best to send the e-mail if (!isset($from) || !Validate::isEmail($from)) { $from = $configuration['PS_SHOP_EMAIL']; } if (!Validate::isEmail($from)) { $from = null; } // $from_name is not that important, no need to die if it is not valid if (!isset($from_name) || !Validate::isMailName($from_name)) { $from_name = $configuration['PS_SHOP_NAME']; } if (!Validate::isMailName($from_name)) { $from_name = null; } // It would be difficult to send an e-mail if the e-mail is not valid, so this time we can die if there is a problem if (!is_array($to) && !Validate::isEmail($to)) { Tools::dieOrLog(Tools::displayError('Error: parameter "to" is corrupted'), $die); return false; } if (!is_array($template_vars)) { $template_vars = array(); } // Do not crash for this error, that may be a complicated customer name if (is_string($to_name) && !empty($to_name) && !Validate::isMailName($to_name)) { $to_name = null; } if (!Validate::isTplName($template)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail template'), $die); return false; } if (!Validate::isMailSubject($subject)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail subject'), $die); return false; } /* Construct multiple recipients list if needed */ $to_list = new Swift_RecipientList(); if (is_array($to) && isset($to)) { foreach ($to as $key => $addr) { $addr = trim($addr); if (!Validate::isEmail($addr)) { Tools::dieOrLog(Tools::displayError('Error: invalid e-mail address'), $die); return false; } if (is_array($to_name)) { if ($to_name && is_array($to_name) && Validate::isGenericName($to_name[$key])) { $to_name = $to_name[$key]; } } if ($to_name == null || $to_name == $addr) { $to_name = ''; } else { if (function_exists('mb_encode_mimeheader')) { $to_name = mb_encode_mimeheader($to_name, 'utf-8'); } else { $to_name = self::mimeEncode($to_name); } } $to_list->addTo($addr, $to_name); } $to_plugin = $to[0]; } else { /* Simple recipient, one address */ $to_plugin = $to; if ($to_name == null || $to_name == $to) { $to_name = ''; } else { if (function_exists('mb_encode_mimeheader')) { $to_name = mb_encode_mimeheader($to_name, 'utf-8'); } else { $to_name = self::mimeEncode($to_name); } } $to_list->addTo($to, $to_name); } if (isset($bcc)) { $to_list->addBcc($bcc); } $to = $to_list; try { /* Connect with the appropriate configuration */ if ($configuration['PS_MAIL_METHOD'] == 2) { if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) { Tools::dieOrLog(Tools::displayError('Error: invalid SMTP server or SMTP port'), $die); return false; } $connection = new Swift_Connection_SMTP($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], $configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'ssl' ? Swift_Connection_SMTP::ENC_SSL : ($configuration['PS_MAIL_SMTP_ENCRYPTION'] == 'tls' ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF)); $connection->setTimeout(4); if (!$connection) { return false; } if (!empty($configuration['PS_MAIL_USER'])) { $connection->setUsername($configuration['PS_MAIL_USER']); } if (!empty($configuration['PS_MAIL_PASSWD'])) { $connection->setPassword($configuration['PS_MAIL_PASSWD']); } } else { $connection = new Swift_Connection_NativeMail(); } if (!$connection) { return false; } $swift = new Swift($connection, Configuration::get('PS_MAIL_DOMAIN', null, null, $id_shop)); /* Get templates content */ $iso = Language::getIsoById((int) $id_lang); if (!$iso) { Tools::dieOrLog(Tools::displayError('Error - No ISO code for email'), $die); return false; } $template = $iso . '/' . $template; $module_name = false; $override_mail = false; // get templatePath if (preg_match('#' . __PS_BASE_URI__ . 'modules/#', str_replace(DIRECTORY_SEPARATOR, '/', $template_path)) && preg_match('#modules/([a-z0-9_-]+)/#ui', str_replace(DIRECTORY_SEPARATOR, '/', $template_path), $res)) { $module_name = $res[1]; } if ($module_name !== false && (file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.txt') || file_exists($theme_path . 'modules/' . $module_name . '/mails/' . $template . '.html'))) { $template_path = $theme_path . 'modules/' . $module_name . '/mails/'; } elseif (file_exists($theme_path . 'mails/' . $template . '.txt') || file_exists($theme_path . 'mails/' . $template . '.html')) { $template_path = $theme_path . 'mails/'; $override_mail = true; } if (!file_exists($template_path . $template . '.txt') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $template . '.txt', $die); return false; } else { if (!file_exists($template_path . $template . '.html') && ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML)) { Tools::dieOrLog(Tools::displayError('Error - The following e-mail template is missing:') . ' ' . $template_path . $template . '.html', $die); return false; } } $template_html = file_get_contents($template_path . $template . '.html'); $template_txt = strip_tags(html_entity_decode(file_get_contents($template_path . $template . '.txt'), null, 'utf-8')); if ($override_mail && file_exists($template_path . $iso . '/lang.php')) { include_once $template_path . $iso . '/lang.php'; } else { if ($module_name && file_exists($theme_path . 'mails/' . $iso . '/lang.php')) { include_once $theme_path . 'mails/' . $iso . '/lang.php'; } else { if (file_exists(_PS_MAIL_DIR_ . $iso . '/lang.php')) { include_once _PS_MAIL_DIR_ . $iso . '/lang.php'; } else { Tools::dieOrLog(Tools::displayError('Error - The lang file is missing for :') . ' ' . $iso, $die); return false; } } } /* Create mail and attach differents parts */ $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME', null, null, $id_shop) . '] ' . $subject); $message->setCharset('utf-8'); /* Set Message-ID - getmypid() is blocked on some hosting */ $message->setId(Mail::generateId()); $message->headers->setEncoding('Q'); if (Configuration::get('PS_LOGO_MAIL') !== false && file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $id_shop); } else { if (file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop))) { $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $id_shop); } else { $template_vars['{shop_logo}'] = ''; } } ShopUrl::cacheMainDomainForShop((int) $id_shop); /* don't attach the logo as */ if (isset($logo)) { $template_vars['{shop_logo}'] = $message->attach(new Swift_Message_EmbeddedFile(new Swift_File($logo), null, ImageManager::getMimeTypeByExtension($logo))); } if (Context::getContext()->link instanceof Link === false) { Context::getContext()->link = new Link(); } $template_vars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME', null, null, $id_shop)); $template_vars['{shop_url}'] = Context::getContext()->link->getPageLink('index', true, Context::getContext()->language->id); $template_vars['{my_account_url}'] = Context::getContext()->link->getPageLink('my-account', true, Context::getContext()->language->id); $template_vars['{guest_tracking_url}'] = Context::getContext()->link->getPageLink('guest-tracking', true, Context::getContext()->language->id); $template_vars['{history_url}'] = Context::getContext()->link->getPageLink('history', true, Context::getContext()->language->id); $template_vars['{color}'] = Tools::safeOutput(Configuration::get('PS_MAIL_COLOR', null, null, $id_shop)); $swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $template_vars)), 'decorator'); if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT) { $message->attach(new Swift_Message_Part($template_txt, 'text/plain', '8bit', 'utf-8')); } if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH || $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML) { $message->attach(new Swift_Message_Part($template_html, 'text/html', '8bit', 'utf-8')); } if ($file_attachment && !empty($file_attachment)) { // Multiple attachments? if (!is_array(current($file_attachment))) { $file_attachment = array($file_attachment); } foreach ($file_attachment as $attachment) { if (isset($attachment['content']) && isset($attachment['name']) && isset($attachment['mime'])) { $message->attach(new Swift_Message_Attachment($attachment['content'], $attachment['name'], $attachment['mime'])); } } } /* Send mail */ $send = $swift->send($message, $to, new Swift_Address($from, $from_name)); $swift->disconnect(); ShopUrl::resetMainDomainCache(); return $send; } catch (Swift_Exception $e) { return false; } }
/** * {@inheritdoc} * * @return $this|self */ public function setCharset($charset) : self { $this->message->setCharset($charset); return $this; }
public function testEmbeddedFilesWithMultipartDataCreateMultipartRelatedContentAsAnAlternative() { $message = new Swift_Message(); $message->setCharset('utf-8'); $message->setSubject('test subject'); $message->addPart('plain part', 'text/plain'); $image = new Swift_Image('<image data>', 'image.gif', 'image/gif'); $cid = $message->embed($image); $message->setBody('<img src="' . $cid . '" />', 'text/html'); $message->setTo(array('*****@*****.**' => 'User')); $message->setFrom(array('*****@*****.**' => 'Other')); $message->setSender(array('*****@*****.**' => 'Other')); $id = $message->getId(); $date = preg_quote(date('r', $message->getDate()), '~'); $boundary = $message->getBoundary(); $cidVal = $image->getId(); $this->assertRegExp('~^' . 'Sender: Other <*****@*****.**>' . "\r\n" . 'Message-ID: <' . $id . '>' . "\r\n" . 'Date: ' . $date . "\r\n" . 'Subject: test subject' . "\r\n" . 'From: Other <*****@*****.**>' . "\r\n" . 'To: User <*****@*****.**>' . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: multipart/alternative;' . "\r\n" . ' boundary="' . $boundary . '"' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: text/plain; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'plain part' . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: multipart/related;' . "\r\n" . ' boundary="(.*?)"' . "\r\n" . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/html; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . '<img.*?/>' . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: image/gif; name=image.gif' . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: inline; filename=image.gif' . "\r\n" . 'Content-ID: <' . $cidVal . '>' . "\r\n" . "\r\n" . preg_quote(base64_encode('<image data>'), '~') . "\r\n\r\n" . '--\\1--' . "\r\n" . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D', $message->toString()); }
public function testHTMLPartAppearsLastEvenWhenAttachmentsAdded() { $message = new Swift_Message(); $message->setCharset('utf-8'); $message->setSubject('test subject'); $message->addPart('plain part', 'text/plain'); $attachment = new Swift_Attachment('<data>', 'image.gif', 'image/gif'); $message->attach($attachment); $message->setBody('HTML part', 'text/html'); $message->setTo(array('*****@*****.**' => 'User')); $message->setFrom(array('*****@*****.**' => 'Other')); $message->setSender(array('*****@*****.**' => 'Other')); $id = $message->getId(); $date = preg_quote($message->getDate()->format('r'), '~'); $boundary = $message->getBoundary(); $this->assertRegExp('~^' . 'Sender: Other <*****@*****.**>' . "\r\n" . 'Message-ID: <' . $id . '>' . "\r\n" . 'Date: ' . $date . "\r\n" . 'Subject: test subject' . "\r\n" . 'From: Other <*****@*****.**>' . "\r\n" . 'To: User <*****@*****.**>' . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: multipart/mixed;' . "\r\n" . ' boundary="' . $boundary . '"' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: multipart/alternative;' . "\r\n" . ' boundary="(.*?)"' . "\r\n" . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/plain; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'plain part' . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/html; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'HTML part' . "\r\n\r\n" . '--\\1--' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: image/gif; name=image.gif' . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: attachment; filename=image.gif' . "\r\n" . "\r\n" . preg_quote(base64_encode('<data>'), '~') . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D', $message->toString()); }
/** * 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; }