/** * Send a Swift Message instance. * * @param \Swift_Message $message * @return int */ protected function sendSwiftMessage($message) { $from = $message->getFrom(); if (empty($from)) { list($sender_addr, $sender_name) = $this->sender_addr; empty($sender_addr) or $message->setFrom($sender_addr, $sender_name); } list($log_addr, $log_name) = $this->log_addr; empty($log_addr) or $message->setBcc($log_addr, $log_name); $to = $message->getTo(); empty($to) or $to = key($to); /* * Set custom headers for tracking */ $headers = $message->getHeaders(); $headers->addTextHeader('X-Site-ID', $this->x_site_id); $headers->addTextHeader('X-User-ID', base64_encode($to)); /* * Set to address based on environment */ if (strcasecmp($this->environment, 'production') != 0) { list($dev_addr, $dev_name) = $this->developer_addr; $message->setTo($dev_addr, $dev_name); } /* * Set return path. */ if ($this->return_path) { $return_path = $this->generateReturnPathEmail(key($message->getTo())); $message->setReturnPath($return_path); } parent::sendSwiftMessage($message); }
public function send(\Swift_Message $message, $tplName, array $tplParams = array()) { if (!$message->getFrom()) { $message->setFrom($this->mailerParams['from']); } if (!$message->getReturnPath()) { $message->setReturnPath($this->mailerParams['return_path']); } $html = $this->templating->render($tplName, $tplParams); $message->setBody($html, 'text/html')->addPart($this->html2text->convert($html), 'text/plain'); if (!$message->getSubject()) { $message->setSubject((new Crawler($html))->filter('head title')->text()); } $this->mailer->send($message); }
/** * Send a message to any number of recipients * @param Swift_Message The message to send. This does not need to (and shouldn't really) have any of the recipient headers set. * @param mixed The recipients to send to. Can be a string, Swift_Address or Swift_RecipientList. Note that all addresses apart from Bcc recipients will appear in the message headers * @param mixed The address to send the message from. Can either be a string or an instance of Swift_Address. * @return int The number of successful recipients * @throws Swift_ConnectionException If sending fails for any reason. */ public function send(Swift_Message $message, $recipients, $from) { Swift_ClassLoader::load("Swift_Message_Encoder"); if (is_string($recipients) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $recipients)) { $recipients = new Swift_Address($recipients); } elseif (!$recipients instanceof Swift_AddressContainer) { throw new Exception("The recipients parameter must either be a valid string email address, " . "an instance of Swift_RecipientList or an instance of Swift_Address."); } if (is_string($from) && preg_match("/^" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\$/", $from)) { $from = new Swift_Address($from); } elseif (!$from instanceof Swift_Address) { throw new Exception("The sender parameter must either be a valid string email address or " . "an instance of Swift_Address."); } $log = Swift_LogContainer::getLog(); if (!$message->getEncoding() && !$this->connection->hasExtension("8BITMIME")) { $message->setEncoding("QP", true, true); } $list = $recipients; if ($recipients instanceof Swift_Address) { $list = new Swift_RecipientList(); $list->addTo($recipients); } Swift_ClassLoader::load("Swift_Events_SendEvent"); $send_event = new Swift_Events_SendEvent($message, $list, $from, 0); $this->notifyListeners($send_event, "BeforeSendListener"); $to = $cc = array(); if (!($has_from = $message->getFrom())) { $message->setFrom($from); } if (!($has_return_path = $message->getReturnPath())) { $message->setReturnPath($from->build(true)); } if (!($has_reply_to = $message->getReplyTo())) { $message->setReplyTo($from); } if (!$has_reply_to[0]) { $message->setReplyTo($from->getAddress()); } if (!($has_message_id = $message->getId())) { $message->generateId(); } $this->command("MAIL FROM: " . $message->getReturnPath(true), 250); $failed = 0; $sent = 0; $tmp_sent = 0; $it = $list->getIterator("to"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); $to[] = $address->build(); try { $this->command("RCPT TO: " . $address->build(true), 250); $tmp_sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } } } $it = $list->getIterator("cc"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); $cc[] = $address->build(); try { $this->command("RCPT TO: " . $address->build(true), 250); $tmp_sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } } } if ($failed == count($to) + count($cc)) { $this->reset(); $this->notifyListeners($send_event, "SendListener"); return 0; } if (!($has_to = $message->getTo()) && !empty($to)) { $message->setTo($to); } if (!($has_cc = $message->getCc()) && !empty($cc)) { $message->setCc($cc); } $this->command("DATA", 354); $data = $message->build(); while (false !== ($bytes = $data->read())) { $this->command($bytes, -1); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("<MESSAGE DATA>", Swift_Log::COMMAND); } try { $this->command("\r\n.", 250); $sent += $tmp_sent; } catch (Swift_BadResponseException $e) { $failed += $tmp_sent; } $tmp_sent = 0; $has_bcc = $message->getBcc(); $it = $list->getIterator("bcc"); while ($it->hasNext()) { $it->next(); $address = $it->getValue(); if (!$has_bcc) { $message->setBcc($address->build()); } try { $this->command("MAIL FROM: " . $message->getReturnPath(true), 250); $this->command("RCPT TO: " . $address->build(true), 250); $this->command("DATA", 354); $data = $message->build(); while (false !== ($bytes = $data->read())) { $this->command($bytes, -1); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("<MESSAGE DATA>", Swift_Log::COMMAND); } $this->command("\r\n.", 250); $sent++; } catch (Swift_BadResponseException $e) { $failed++; $send_event->addFailedRecipient($address->getAddress()); if ($log->hasLevel(Swift_Log::LOG_FAILURES)) { $log->addfailedRecipient($address->getAddress()); } $this->reset(); } } $total = count($to) + count($cc) + count($list->getBcc()); $send_event->setNumSent($sent); $this->notifyListeners($send_event, "SendListener"); if (!$has_return_path) { $message->setReturnPath(""); } if (!$has_from) { $message->setFrom(""); } if (!$has_to) { $message->setTo(""); } if (!$has_reply_to) { $message->setReplyTo(null); } if (!$has_cc) { $message->setCc(null); } if (!$has_bcc) { $message->setBcc(null); } if (!$has_message_id) { $message->setId(null); } if ($log->hasLevel(Swift_Log::LOG_NETWORK)) { $log->add("Message sent to " . $sent . "/" . $total . " recipients", Swift_Log::NORMAL); } return $sent; }
/** * Returns a Swift_Message instance that can be sent * * @return \Swift_Message */ public function getSwiftMessage() { $message = new \Swift_Message(); $message->setDate($this->getDate()->getTimestamp()); $message->setFrom($this->getFrom()); $message->setReplyTo($this->getReplyTo()); $message->setReturnPath($this->getReturnPath()); $message->setTo($this->getTo()); $message->setCc($this->getCc()); $message->setBcc($this->getBcc()); $message->setSubject($this->getSubject()); $message->setBody($this->getBody()); return $message; }
/** * Set the "return path" of the message. * * @param string $address * @return $this */ public function returnPath($address) { $this->swift->setReturnPath($address); return $this; }
/** * 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); } }
/** * Set the return path address (where bounces go to) * @param mixed The address as a string or Swift_Address */ public function setReturnPath($address) { return $this->message->setReturnPath($address); }
/** * Sends notifications *now* * @param mixed $to string or array...the type of address (email, task ID, user ID) is specified below * @param integer $to_type type of $to address * @param integer $type type of notification * @param array $data additional info needed for notification * @access public * @return bool */ function send_now($to, $to_type, $type, $data = array()) { global $db, $fs, $proj; $emails = array(); $jids = array(); $result = true; if (defined('FS_NO_MAIL')) { return true; } switch ($to_type) { case ADDRESS_DONE: // from send_stored() list($emails, $jids) = $to; $data = unserialize($data['message_data']); $subject = $data['subject']; $body = $data['body']; break; case ADDRESS_EMAIL: // this happens on email confirmation, when no user exists $emails = is_array($to) ? $to : array($to); break; case ADDRESS_USER: // list of user IDs list($emails, $jids) = Notifications::user_to_address($to, $type); break; case ADDRESS_TASK: // now we need everyone on the notification list and the assignees list($emails, $jids) = Notifications::task_notifications($to, $type, ADDRESS_EMAIL); $data['task_id'] = $to; break; } if (isset($data['task_id'])) { $data['task'] = Flyspray::getTaskDetails($data['task_id']); // we have project specific options $pid = $db->x->GetOne('SELECT project_id FROM {tasks} WHERE task_id = ?', null, $data['task_id']); $data['project'] = new Project($pid); } if ($to_type != ADDRESS_DONE) { list($subject, $body) = Notifications::generate_message($type, $data); } if (isset($data['task_id'])) { // Now, we add the project contact addresses, // but only if the task is public $data['task'] = Flyspray::getTaskDetails($data['task_id']); if ($data['task']['mark_private'] != '1' && in_array($type, explode(' ', $data['project']->prefs['notify_types']))) { $proj_emails = preg_split('/[\\s,;]+/', $proj->prefs['notify_email'], -1, PREG_SPLIT_NO_EMPTY); $proj_jids = preg_split('/[\\s,;]+/', $proj->prefs['notify_jabber'], -1, PREG_SPLIT_NO_EMPTY); $emails = array_merge($proj_emails, $emails); if ($fs->prefs['global_email']) { $emails[] = $fs->prefs['global_email']; } if ($fs->prefs['global_jabber']) { $jids[] = $fs->prefs['global_jabber']; } $jids = array_merge($proj_jids, $emails); } } // Now we start sending if (count($emails)) { Swift_ClassLoader::load('Swift_Connection_Multi'); Swift_ClassLoader::load('Swift_Connection_SMTP'); $pool = new Swift_Connection_Multi(); // first choose method if ($fs->prefs['smtp_server']) { $split = explode(':', $fs->prefs['smtp_server']); $port = null; if (count($split) == 2) { $fs->prefs['smtp_server'] = $split[0]; $port = $split[1]; } // connection... SSL, TLS or none if ($fs->prefs['email_ssl']) { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port ? $port : SWIFT_SMTP_PORT_SECURE, SWIFT_SMTP_ENC_SSL); } else { if ($fs->prefs['email_tls']) { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port ? $port : SWIFT_SMTP_PORT_SECURE, SWIFT_SMTP_ENC_TLS); } else { $smtp = new Swift_Connection_SMTP($fs->prefs['smtp_server'], $port); } } if ($fs->prefs['smtp_user']) { $smtp->setUsername($fs->prefs['smtp_user']); $smtp->setPassword($fs->prefs['smtp_pass']); } if (defined('FS_SMTP_TIMEOUT')) { $smtp->setTimeout(FS_SMTP_TIMEOUT); } $pool->addConnection($smtp); } else { Swift_ClassLoader::load('Swift_Connection_NativeMail'); // a connection to localhost smtp server as fallback, discarded if there is no such thing available. $pool->addConnection(new Swift_Connection_SMTP()); $pool->addConnection(new Swift_Connection_NativeMail()); } $swift = new Swift($pool); if (isset($data['task_id'])) { $swift->attachPlugin(new NotificationsThread($data['task_id'], $emails, $db), 'MessageThread'); } if (defined('FS_MAIL_DEBUG')) { $swift->log->enable(); Swift_ClassLoader::load('Swift_Plugin_VerboseSending'); $view = new Swift_Plugin_VerboseSending_DefaultView(); $swift->attachPlugin(new Swift_Plugin_VerboseSending($view), "verbose"); } $message = new Swift_Message($subject, $body); // check for reply-to if (isset($data['project']) && $data['project']->prefs['notify_reply']) { $message->setReplyTo($data['project']->prefs['notify_reply']); } if (isset($data['project']) && isset($data['project']->prefs['bounce_address'])) { $message->setReturnPath($data['project']->prefs['bounce_address']); } $message->headers->setCharset('utf-8'); $message->headers->set('Precedence', 'list'); $message->headers->set('X-Mailer', 'Flyspray'); // Add custom headers, possibly if (isset($data['headers'])) { $headers = array_map('trim', explode("\n", $data['headers'])); if ($headers = array_filter($headers)) { foreach ($headers as $header) { list($name, $value) = explode(':', $header); $message->headers->set(sprintf('X-Flyspray-%s', $name), $value); } } } $recipients = new Swift_RecipientList(); $recipients->addTo($emails); // && $result purpose: if this has been set to false before, it should never become true again // to indicate an error $result = $swift->batchSend($message, $recipients, $fs->prefs['admin_email']) === count($emails) && $result; if (isset($data['task_id'])) { $plugin =& $swift->getPlugin('MessageThread'); if (count($plugin->thread_info)) { $stmt = $db->x->autoPrepare('{notification_threads}', array('task_id', 'recipient_id', 'message_id')); $db->x->executeMultiple($stmt, $plugin->thread_info); $stmt->free(); } } $swift->disconnect(); } if (count($jids)) { $jids = array_unique($jids); if (!$fs->prefs['jabber_username'] || !$fs->prefs['jabber_password']) { return $result; } // nothing that can't be guessed correctly ^^ if (!$fs->prefs['jabber_port']) { $fs->prefs['jabber_port'] = 5222; } require_once 'class.jabber2.php'; $jabber = new Jabber($fs->prefs['jabber_username'], $fs->prefs['jabber_password'], $fs->prefs['jabber_security'], $fs->prefs['jabber_port'], $fs->prefs['jabber_server']); $jabber->SetResource('flyspray'); $jabber->login(); foreach ($jids as $jid) { $result = $jabber->send_message($jid, $body, $subject, 'normal') && $result; } } return $result; }
/** * {@inheritdoc} * * @return $this|self */ public function setReturnPath($address) : self { $this->message->setReturnPath($address); return $this; }
/** * Defines the return path for the email. * By default it should be set to the sender. * * @param string $returnPath * * @return $this */ public function setReturnPath($returnPath) { $this->message->setReturnPath($returnPath); return $this; }
/** * Set the return-path (the bounce address) of this message. * * @param string $address * @return \TYPO3\CMS\Core\Mail\MailMessage */ public function setReturnPath($address) { $address = $this->idnaEncodeAddresses($address); return parent::setReturnPath($address); }
/** * Send an email using this server. * * @param \Swift_Message $message The email message to send. * * @return int (number of successful recipients) */ public function send(\Swift_Message $message) { # Set the bounce return path if one has been specified if ($this->returnPath) { $message->setReturnPath($this->returnPath); } return $this->getMailer()->send($message); }
/** * 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; }