Ejemplo n.º 1
2
 public function sendMessage()
 {
     $transport = \Swift_SmtpTransport::newInstance($this->mta->address, $this->mta->port);
     $swift = \Swift_Mailer::newInstance($transport);
     $message = new \Swift_Message();
     $headers = $message->getHeaders();
     $headers->addTextHeader('X-GreenArrow-MailClass', 'SIGMA_NEWEMKTG_DEVEL');
     $message->setSubject($this->data->subject);
     $message->setFrom(array($this->data->fromEmail => $this->data->fromName));
     $message->setBody($this->html, 'text/html');
     $message->addPart($this->plainText, 'text/plain');
     $this->logger->log("Crea contenido del correo para enviar");
     foreach ($this->data->target as $to) {
         $message->setTo($to);
         $this->logger->log("Preparandose para enviar mensaje a: {$to}");
         $recipients = $swift->send($message, $failures);
         if ($recipients) {
             \Phalcon\DI::getDefault()->get('logger')->log('Recover Password Message successfully sent!');
         } else {
             throw new Exception('Error while sending message: ' . $failures);
         }
     }
 }
 /**
  * Create activity from Swift Message
  * @param  \Swift_Message $message 
  * @return EmailActivity
  */
 protected function createActivity(\Swift_Message $message)
 {
     // Creation du doc de trace d'activité avec les données basiques
     $from_email = $message->getHeaders()->get('From')->getFieldBody();
     $to_email = $message->getHeaders()->get('To')->getFieldBody();
     $message_id = $message->getHeaders()->get('Message-ID')->getId();
     $subject = $message->getSubject();
     $activity = new $this->activity_class();
     $activity->setFromEmail($from_email);
     $activity->setToEmail($to_email);
     $activity->setSubject($subject);
     $activity->setMessageId($message_id);
     // Récupération du document associé aux relations from_user et to_user
     $meta = $this->dm->getClassMetadata($this->activity_class);
     $class = $meta->getAssociationTargetClass('from_user');
     $repo = $this->dm->getRepository($class);
     $user = $repo->findOneByEmail($activity->getFromEmail());
     if (!is_null($user)) {
         $activity->setFromUser($user);
     }
     $class = $meta->getAssociationTargetClass('to_user');
     $repo = $this->dm->getRepository($class);
     $user = $repo->findOneByEmail($activity->getToEmail());
     if (!is_null($user)) {
         $activity->setToUser($user);
     }
     return $activity;
 }
Ejemplo n.º 3
0
 /**
  * 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);
 }
Ejemplo n.º 4
0
 public function testSend()
 {
     $message = new Swift_Message();
     $message->setFrom('*****@*****.**', 'Johnny #5');
     $message->setSubject('Is alive!');
     $message->addTo('*****@*****.**', 'A. Friend');
     $message->addTo('*****@*****.**');
     $message->addCc('*****@*****.**');
     $message->addCc('*****@*****.**', 'Extra 2');
     $message->addBcc('*****@*****.**');
     $message->addBcc('*****@*****.**', 'Extra 4');
     $message->addPart('<q>Help me Rhonda</q>', 'text/html');
     $message->addPart('Doo-wah-ditty.', 'text/plain');
     $attachment = Swift_Attachment::newInstance('This is the plain text attachment.', 'hello.txt', 'text/plain');
     $attachment2 = Swift_Attachment::newInstance('This is the plain text attachment.', 'hello.txt', 'text/plain');
     $attachment2->setDisposition('inline');
     $message->attach($attachment);
     $message->attach($attachment2);
     $message->setPriority(1);
     $headers = $message->getHeaders();
     $headers->addTextHeader('X-PM-Tag', 'movie-quotes');
     $messageId = $headers->get('Message-ID')->getId();
     $transport = new PostmarkTransportStub('TESTING_SERVER');
     $client = $this->getMock('GuzzleHttp\\Client', array('request'));
     $transport->setHttpClient($client);
     $o = PHP_OS;
     $v = phpversion();
     $client->expects($this->once())->method('request')->with($this->equalTo('POST'), $this->equalTo('https://api.postmarkapp.com/email'), $this->equalTo(['headers' => ['X-Postmark-Server-Token' => 'TESTING_SERVER', 'User-Agent' => "swiftmailer-postmark (PHP Version: {$v}, OS: {$o})", 'Content-Type' => 'application/json'], 'json' => ['From' => '"Johnny #5" <*****@*****.**>', 'To' => '"A. Friend" <*****@*****.**>,you+two@example.com', 'Cc' => 'another+1@example.com,"Extra 2" <*****@*****.**>', 'Bcc' => 'another+3@example.com,"Extra 4" <*****@*****.**>', 'Subject' => 'Is alive!', 'Tag' => 'movie-quotes', 'TextBody' => 'Doo-wah-ditty.', 'HtmlBody' => '<q>Help me Rhonda</q>', 'Headers' => [['Name' => 'Message-ID', 'Value' => '<' . $messageId . '>'], ['Name' => 'X-PM-KeepID', 'Value' => 'true'], ['Name' => 'X-Priority', 'Value' => '1 (Highest)']], 'Attachments' => [['ContentType' => 'text/plain', 'Content' => 'VGhpcyBpcyB0aGUgcGxhaW4gdGV4dCBhdHRhY2htZW50Lg==', 'Name' => 'hello.txt'], ['ContentType' => 'text/plain', 'Content' => 'VGhpcyBpcyB0aGUgcGxhaW4gdGV4dCBhdHRhY2htZW50Lg==', 'Name' => 'hello.txt', 'ContentID' => 'cid:' . $attachment2->getId()]]]]));
     $transport->send($message);
 }
Ejemplo n.º 5
0
 /**
  * Send the message.
  *
  * @return MailInterface The current instance
  */
 protected function setHeaders() : MailInterface
 {
     $this->swiftMessage->getHeaders()->addTextHeader('X-Mailer', $this->get('X-Mailer'));
     $this->swiftMessage->getHeaders()->addTextHeader('X-UCSDMATH-MESSAGE-ID', $this->get('X-UCSDMATH-MESSAGE-ID'));
     $this->swiftMessage->getHeaders()->addTextHeader('X-UCSDMATH-APPLICATION', $this->get('X-UCSDMATH-APPLICATION'));
     $this->swiftMessage->getHeaders()->addTextHeader('X-UCSDMATH-METHOD', $this->get('X-UCSDMATH-METHOD'));
     return $this;
 }
Ejemplo n.º 6
0
 /**
  * Get all headers from the message.
  *
  * @return array
  */
 public function getHeaders()
 {
     $swiftHeaders = $this->message->getHeaders()->listAll();
     $headers = [];
     foreach ($swiftHeaders as $headerName) {
         $headers[$headerName] = $this->getHeader($headerName);
     }
     return $headers;
 }
 public function testListUnsubscribe()
 {
     $transport = $this->createTransport();
     $message = new \Swift_Message('Test Subject', 'Foo bar');
     $message->addTo('*****@*****.**', 'To Name')->addFrom('*****@*****.**', 'From Name');
     $message->getHeaders()->addTextHeader('List-Unsubscribe', '<mailto:unsubscribe@example.com>');
     $mandrillMessage = $transport->getMandrillMessage($message);
     $this->assertEquals('<mailto:unsubscribe@example.com>', $mandrillMessage['headers']['List-Unsubscribe']);
     $this->assertMessageSendable($message);
 }
Ejemplo n.º 8
0
 public function testTags()
 {
     $transport = $this->createTransport();
     $message = new \Swift_Message('Test Subject', 'Foo bar');
     $message->addTo('*****@*****.**', 'To Name')->addFrom('*****@*****.**', 'From Name');
     $message->getHeaders()->addTextHeader('X-MC-Tags', 'foo,bar');
     $mandrillMessage = $transport->getMandrillMessage($message);
     $this->assertEquals('foo', $mandrillMessage['tags'][0]);
     $this->assertEquals('bar', $mandrillMessage['tags'][1]);
     $this->assertMessageSendable($message);
 }
 public function testUnstructuredHeaderSlashesShouldNotBeEscaped()
 {
     $complicated_header = array('to' => array('*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'), 'sub' => array('-name-' => array('email1', '"email2"', 'email3\\', 'email4', 'email5'), '-url-' => array('http://google.com', 'http://yahoo.com', 'http://hotmail.com', 'http://aol.com', 'http://facebook.com')));
     $json = json_encode($complicated_header);
     $message = new Swift_Message();
     $headers = $message->getHeaders();
     $headers->addTextHeader('X-SMTPAPI', $json);
     $header = $headers->get('X-SMTPAPI');
     $this->assertEquals('Swift_Mime_Headers_UnstructuredHeader', get_class($header));
     $this->assertEquals($json, $header->getFieldBody());
 }
Ejemplo n.º 10
0
 /**
  *
  * @param stream $stream
  * @param boolean $fillHeaders (default to false)
  * @param \Swift_Mime_MimeEntity $message (default to null)
  * @return Swift_Mime_MimeEntity|\Swift_Message
  */
 public function parseStream($stream, $fillHeaders = false, \Swift_Mime_MimeEntity $message = null)
 {
     $partHeaders = $this->extractHeaders($stream);
     $filteredHeaders = $this->filterHeaders($partHeaders);
     $parts = $this->parseParts($stream, $partHeaders);
     if (!$message) {
         $message = new \Swift_Message();
     }
     $headers = $this->createHeadersSet($filteredHeaders);
     foreach ($headers->getAll() as $name => $header) {
         if ($fillHeaders || in_array(strtolower($header->getFieldName()), $this->allowedHeaders)) {
             $message->getHeaders()->set($header);
         }
     }
     $this->createMessage($parts, $message);
     return $message;
 }
Ejemplo n.º 11
0
 /**
  * Add a custom text header
  *
  * @param string $strKey   The header name
  * @param string $strValue The header value
  */
 public function addHeader($strKey, $strValue)
 {
     $this->objMessage->getHeaders()->addTextHeader($strKey, $strValue);
 }
 /**
  * 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);
     }
 }
 /**
  * Converts \Swift_Message into associative array.
  *
  * @param array      $search            If the mailer requires tokens in another format than Mautic's, pass array of Mautic tokens to replace
  * @param array      $replace           If the mailer requires tokens in another format than Mautic's, pass array of replacement tokens
  * @param bool|false $binaryAttachments True to convert file attachments to binary
  *
  * @return array|\Swift_Message
  */
 protected function messageToArray($search = [], $replace = [], $binaryAttachments = false)
 {
     if (!empty($search)) {
         MailHelper::searchReplaceTokens($search, $replace, $this->message);
     }
     $from = $this->message->getFrom();
     $fromEmail = current(array_keys($from));
     $fromName = $from[$fromEmail];
     $message = ['html' => $this->message->getBody(), 'text' => MailHelper::getPlainTextFromMessage($this->message), 'subject' => $this->message->getSubject(), 'from' => ['name' => $fromName, 'email' => $fromEmail]];
     // Generate the recipients
     $message['recipients'] = ['to' => [], 'cc' => [], 'bcc' => []];
     $to = $this->message->getTo();
     foreach ($to as $email => $name) {
         $message['recipients']['to'][$email] = ['email' => $email, 'name' => $name];
     }
     $cc = $this->message->getCc();
     if (!empty($cc)) {
         foreach ($cc as $email => $name) {
             $message['recipients']['cc'][$email] = ['email' => $email, 'name' => $name];
         }
     }
     $bcc = $this->message->getBcc();
     if (!empty($bcc)) {
         foreach ($bcc as $email => $name) {
             $message['recipients']['bcc'][$email] = ['email' => $email, 'name' => $name];
         }
     }
     $replyTo = $this->message->getReplyTo();
     if (!empty($replyTo)) {
         foreach ($replyTo as $email => $name) {
             $message['replyTo'] = ['email' => $email, 'name' => $name];
         }
     }
     $returnPath = $this->message->getReturnPath();
     if (!empty($returnPath)) {
         $message['returnPath'] = $returnPath;
     }
     // Attachments
     $children = $this->message->getChildren();
     $attachments = [];
     foreach ($children as $child) {
         if ($child instanceof \Swift_Attachment) {
             $attachments[] = ['type' => $child->getContentType(), 'name' => $child->getFilename(), 'content' => $child->getEncoder()->encodeString($child->getBody())];
         }
     }
     if ($binaryAttachments) {
         // Convert attachments to binary if applicable
         $message['attachments'] = $attachments;
         $fileAttachments = $this->getAttachments();
         if (!empty($fileAttachments)) {
             foreach ($fileAttachments as $attachment) {
                 if (file_exists($attachment['filePath']) && is_readable($attachment['filePath'])) {
                     try {
                         $swiftAttachment = \Swift_Attachment::fromPath($attachment['filePath']);
                         if (!empty($attachment['fileName'])) {
                             $swiftAttachment->setFilename($attachment['fileName']);
                         }
                         if (!empty($attachment['contentType'])) {
                             $swiftAttachment->setContentType($attachment['contentType']);
                         }
                         if (!empty($attachment['inline'])) {
                             $swiftAttachment->setDisposition('inline');
                         }
                         $message['attachments'][] = ['type' => $swiftAttachment->getContentType(), 'name' => $swiftAttachment->getFilename(), 'content' => $swiftAttachment->getEncoder()->encodeString($swiftAttachment->getBody())];
                     } catch (\Exception $e) {
                         error_log($e);
                     }
                 }
             }
         }
     } else {
         $message['binary_attachments'] = $attachments;
         $message['file_attachments'] = $this->getAttachments();
     }
     $message['headers'] = [];
     $headers = $this->message->getHeaders()->getAll();
     /** @var \Swift_Mime_Header $header */
     foreach ($headers as $header) {
         if ($header->getFieldType() == \Swift_Mime_Header::TYPE_TEXT) {
             $message['headers'][$header->getFieldName()] = $header->getFieldBodyModel();
         }
     }
     return $message;
 }
Ejemplo n.º 14
0
 public static function sendEmail($subject, $user_id, $toaddress, $message_text, $message_title, $encoded_html = false)
 {
     // pulling out just the TO email from a 'Address Name <*****@*****.**>' style address:
     if (strpos($toaddress, '>')) {
         preg_match('/([^<]+)\\s<(.*)>/', $toaddress, $matches);
         if (count($matches)) {
             $toaddress = $matches[2];
         }
     }
     // if the email is bullshit don't try to send to it:
     if (!filter_var($toaddress, FILTER_VALIDATE_EMAIL)) {
         return false;
     }
     // TODO: look up user settings for email if user_id is set — allow for multiple SMTP settings
     // on a per-user basis in the multi-user system
     $email_settings = CASHSystem::getDefaultEmail(true);
     if (CASHSystem::getSystemSettings('instancetype') == 'multi' && $user_id) {
         $user_request = new CASHRequest(array('cash_request_type' => 'people', 'cash_action' => 'getuser', 'user_id' => $user_id));
         $user_details = $user_request->response['payload'];
         $setname = false;
         if (trim($user_details['display_name'] . '') !== '' && $user_details['display_name'] !== 'Anonymous') {
             $setname = $user_details['display_name'];
         }
         if (!$setname && $user_details['username']) {
             $setname = $user_details['username'];
         }
         if ($setname) {
             $fromaddress = $setname . ' <' . $user_details['email_address'] . '>';
         } else {
             $fromaddress = $user_details['email_address'];
         }
     } else {
         $fromaddress = $email_settings['systememail'];
     }
     // let's deal with complex versus simple email addresses. if we find '>' present we try
     // parsing for name + address from a 'Address Name <*****@*****.**>' style email:
     if (strpos($fromaddress, '>')) {
         preg_match('/([^<]+)\\s<(.*)>/', $fromaddress, $matches);
         if (count($matches)) {
             $from = array($matches[2] => $matches[1]);
         } else {
             $from = $fromaddress;
         }
     } else {
         $from = $fromaddress;
     }
     // handle encoding of HTML if specific HTML isn't passed in:
     if (!$encoded_html) {
         $template = @file_get_contents(CASH_PLATFORM_ROOT . '/settings/defaults/system_email.mustache');
         if (file_exists(CASH_PLATFORM_ROOT . '/lib/markdown/markdown.php')) {
             include_once CASH_PLATFORM_ROOT . '/lib/markdown/markdown.php';
         }
         $message_text = Markdown($message_text);
         $encoded_html = preg_replace('/(\\shttp:\\/\\/(\\S*))/', '<a href="\\1">\\1</a>', $message_text);
         if (!$template) {
             $encoded_html .= '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>' . $message_title . '</title></head><body>' . "<h1>{$message_title}</h1>\n" . "<p>" . $encoded_html . "</p>" . "</body></html>";
         } else {
             // open up some mustache in here:
             include_once CASH_PLATFORM_ROOT . '/lib/mustache/Mustache.php';
             $higgins = new Mustache();
             $mustache_vars = array('encoded_html' => $encoded_html, 'message_title' => $message_title, 'cdn_url' => defined('CDN_URL') ? CDN_URL : CASH_ADMIN_URL);
             $encoded_html = $higgins->render($template, $mustache_vars);
         }
     }
     // deal with SMTP settings later:
     $smtp = $email_settings['smtp'];
     // include swift mailer
     include_once CASH_PLATFORM_ROOT . '/lib/swift/swift_required.php';
     if ($smtp) {
         // use SMTP settings for goodtimes robust happy mailing
         $transport = Swift_SmtpTransport::newInstance($email_settings['smtpserver'], $email_settings['smtpport']);
         if ($email_settings['smtpusername']) {
             $transport->setUsername($email_settings['smtpusername']);
             $transport->setPassword($email_settings['smtppassword']);
         }
     } else {
         // aww shit. use mail() and hope it gets there
         $transport = Swift_MailTransport::newInstance();
     }
     $swift = Swift_Mailer::newInstance($transport);
     $message = new Swift_Message($subject);
     $message->setFrom($from);
     $message->setBody($encoded_html, 'text/html');
     $message->setTo($toaddress);
     $message->addPart($message_text, 'text/plain');
     $headers = $message->getHeaders();
     $headers->addTextHeader('X-MC-Track', 'opens');
     // Mandrill-specific tracking...leave in by defauly, no harm if not Mandrill
     if ($recipients = $swift->send($message, $failures)) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 15
0
function mailTo_SendGrid($subject, $from = '*****@*****.**', $to, $html, $text, $hdr)
{
    global $hdr;
    // Your SendGrid account credentials
    $username = '******';
    $password = '******';
    // Create new swift connection and authenticate
    $transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 465, 'ssl');
    $transport->setUsername($username);
    $transport->setPassword($password);
    $swift = Swift_Mailer::newInstance($transport);
    // Create a message (subject)
    $message = new Swift_Message($subject);
    // add SMTPAPI header to the message
    $headers = $message->getHeaders();
    $headers->addTextHeader('X-SMTPAPI', $hdr->asJSON());
    // attach the body of the email
    $message->setFrom($from);
    $message->setBody($html, 'text/html');
    $message->setTo($to);
    $message->addPart($text, 'text/plain');
    // send out the emails
    //return $swift->send($message, $failures);
    if ($recipients = $swift->send($message, $failures)) {
        // This will let us know how many users received this message
        // If we specify the names in the X-SMTPAPI header, then this will always be 1.
        //echo 'Message blasted '.$recipients.' users'; // This will break the jSON signup process if turned on.
    } else {
        // something went wrong =(
        print_r($failures);
    }
}
Ejemplo n.º 16
0
 /**
  * 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);
         }
     }
 }
Ejemplo n.º 17
0
 /**
  * {@inheritdoc}
  */
 public function getHeaders()
 {
     return $this->message->getHeaders();
 }
 /**
  * Handle the event.
  *
  * @param \Swift_Message $message
  * @return void
  */
 public function handle(\Swift_Message $message)
 {
     DB::table('email_log')->insert(['date' => date('Y-m-d H:i:s'), 'email_from' => $message->getHeaders()->get('From')->getFieldBody(), 'email_to' => $message->getHeaders()->get('To')->getFieldBody(), 'email_reply' => '', 'subject' => $message->getHeaders()->get('Subject')->getFieldBody(), 'body' => $this->getMimeEntityString($message)]);
 }
Ejemplo n.º 19
0
 function SendEmail($to, $subject, $body, $task_id = null)
 {
     global $fs, $proj, $user;
     if (empty($to) || empty($to[0])) {
         return;
     }
     // Do we want to use a remote mail server?
     if (!empty($fs->prefs['smtp_server'])) {
         // connection... SSL, TLS or none
         if ($fs->prefs['email_tls']) {
             $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 587, 'tls');
         } else {
             if ($fs->prefs['email_ssl']) {
                 $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 465, 'ssl');
             } else {
                 $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server']);
             }
         }
         if ($fs->prefs['smtp_user']) {
             $swiftconn->setUsername($fs->prefs['smtp_user']);
         }
         if ($fs->prefs['smtp_pass']) {
             $swiftconn->setPassword($fs->prefs['smtp_pass']);
         }
         if (defined('FS_SMTP_TIMEOUT')) {
             $swiftconn->setTimeout(FS_SMTP_TIMEOUT);
         }
         // Use php's built-in mail() function
     } else {
         $swiftconn = Swift_MailTransport::newInstance();
     }
     if (defined('FS_MAIL_LOGFILE')) {
         // FIXME: Swift_LogContainer exists no more???
         // See http://swiftmailer.org/docs/plugins.html#logger-plugin
         // for the new implementation.
         // $log = Swift_LogContainer::getLog();
         // $log->setLogLevel(SWIFT_LOG_EVERYTHING);
     }
     // Make plaintext URLs into hyperlinks, but don't disturb existing ones!
     $htmlbody = preg_replace("/(?<!\")(https?:\\/\\/)([a-zA-Z0-9\\-.]+\\.[a-zA-Z0-9\\-]+([\\/]([a-zA-Z0-9_\\/\\-.?&%=+#])*)*)/", '<a href="$1$2">$2</a>', $body);
     $htmlbody = str_replace("\n", "<br>", $htmlbody);
     // Those constants used were introduced in 5.4.
     if (version_compare(phpversion(), '5.4.0', '<')) {
         $plainbody = html_entity_decode(strip_tags($body));
     } else {
         $plainbody = html_entity_decode(strip_tags($body), ENT_COMPAT | ENT_HTML401, 'utf-8');
     }
     $swift = Swift_Mailer::newInstance($swiftconn);
     $message = new Swift_Message($subject);
     if (isset($fs->prefs['emailNoHTML']) && $fs->prefs['emailNoHTML'] == '1') {
         $message->setBody($plainbody, 'text/plain');
     } else {
         $message->setBody($htmlbody, 'text/html');
         $message->addPart($plainbody, 'text/plain');
     }
     $type = $message->getHeaders()->get('Content-Type');
     $type->setParameter('charset', 'utf-8');
     $message->getHeaders()->addTextHeader('Precedence', 'list');
     $message->getHeaders()->addTextHeader('X-Mailer', 'Flyspray');
     if ($proj->prefs['notify_reply']) {
         $message->setReplyTo($proj->prefs['notify_reply']);
     }
     if (isset($task_id)) {
         $hostdata = parse_url($GLOBALS['baseurl']);
         $inreplyto = sprintf('<FS%d@%s>', $task_id, $hostdata['host']);
         // see http://cr.yp.to/immhf/thread.html this does not seems to work though :(
         $message->getHeaders()->addTextHeader('In-Reply-To', $inreplyto);
         $message->getHeaders()->addTextHeader('References', $inreplyto);
     }
     // now accepts string , array or Swift_Address.
     $message->setTo($to);
     $message->setFrom(array($fs->prefs['admin_email'] => $proj->prefs['project_title']));
     $swift->send($message);
     /* FIXME: Swift_LogContainer exists no more???
        if(defined('FS_MAIL_LOGFILE')) {
            if(is_writable(dirname(FS_MAIL_LOGFILE))) {
                if($fh = fopen(FS_MAIL_LOGFILE, 'ab')) {
                    fwrite($fh, $log->dump(true));
                    fwrite($fh, php_uname());
                    fclose($fh);
                }
            }
        }
        */
     return true;
 }
Ejemplo n.º 20
0
 function SendEmail($to, $subject, $body, $task_id = null)
 {
     global $fs, $proj, $user;
     if (empty($to) || empty($to[0])) {
         return;
     }
     // Do we want to use a remote mail server?
     if (!empty($fs->prefs['smtp_server'])) {
         // connection... SSL, TLS or none
         if ($fs->prefs['email_tls']) {
             $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 587, 'tls');
         } else {
             if ($fs->prefs['email_ssl']) {
                 $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server'], 465, 'ssl');
             } else {
                 $swiftconn = Swift_SmtpTransport::newInstance($fs->prefs['smtp_server']);
             }
         }
         if ($fs->prefs['smtp_user']) {
             $swiftconn->setUsername($fs->prefs['smtp_user']);
             $swiftconn->setPassword($fs->prefs['smtp_pass']);
         }
         if (defined('FS_SMTP_TIMEOUT')) {
             $swiftconn->setTimeout(FS_SMTP_TIMEOUT);
         }
         // Use php's built-in mail() function
     } else {
         $swiftconn = Swift_MailTransport::newInstance();
     }
     if (defined('FS_MAIL_LOGFILE')) {
         $log = Swift_LogContainer::getLog();
         $log->setLogLevel(SWIFT_LOG_EVERYTHING);
     }
     $swift = Swift_Mailer::newInstance($swiftconn);
     $message = new Swift_Message($subject);
     $message->setBody($body);
     $type = $message->getHeaders()->get('Content-Type');
     $type->setValue('text/plain');
     $type->setParameter('charset', 'utf-8');
     $message->getHeaders()->addTextHeader('Precedence', 'list');
     $message->getHeaders()->addTextHeader('X-Mailer', 'Flyspray');
     if ($proj->prefs['notify_reply']) {
         $message->setReplyTo($proj->prefs['notify_reply']);
     }
     if (isset($task_id)) {
         $hostdata = parse_url($GLOBALS['baseurl']);
         $inreplyto = sprintf('<FS%d@%s>', $task_id, $hostdata['host']);
         // see http://cr.yp.to/immhf/thread.html this does not seems to work though :(
         $message->getHeaders()->addTextHeader('In-Reply-To', $inreplyto);
         $message->getHeaders()->addTextHeader('References', $inreplyto);
     }
     // now accepts string , array or Swift_Address.
     $message->setTo($to);
     $message->setFrom(array($fs->prefs['admin_email'] => $proj->prefs['project_title']));
     $swift->send($message);
     if (defined('FS_MAIL_LOGFILE')) {
         if (is_writable(dirname(FS_MAIL_LOGFILE))) {
             if ($fh = fopen(FS_MAIL_LOGFILE, 'ab')) {
                 fwrite($fh, $log->dump(true));
                 fwrite($fh, php_uname());
                 fclose($fh);
             }
         }
     }
     return true;
 }
Ejemplo n.º 21
0
 /**
  * Adds the {@see Email::additionalHeaders} to the message.
  *
  * @param Email $notification
  * @param \Swift_Message $email
  */
 protected function addHeaders(Email $notification, \Swift_Message $email)
 {
     $headers = $email->getHeaders();
     foreach ($notification->getAdditionalHeaders() as $key => $value) {
         if ($value instanceof \DateTime) {
             $headers->addDateHeader($key, $value);
         } else {
             $headers->addTextHeader($key, $value);
         }
     }
 }
Ejemplo n.º 22
0
 /**
  * Merges an OutputByteStream to Swift_Message.
  *
  * @param Swift_OutputByteStream $fromStream
  * @param Swift_Message          $message
  */
 protected function streamToMime(Swift_OutputByteStream $fromStream, Swift_Message $message)
 {
     $bufferLength = 78;
     $headerData = '';
     $fromStream->setReadPointer(0);
     while (($buffer = $fromStream->read($bufferLength)) !== false) {
         $headerData .= $buffer;
         if (false !== strpos($buffer, "\r\n\r\n")) {
             break;
         }
     }
     $headersPosEnd = strpos($headerData, "\r\n\r\n");
     $headerData = trim($headerData);
     $headerData = substr($headerData, 0, $headersPosEnd);
     $headerLines = explode("\r\n", $headerData);
     unset($headerData);
     $headers = array();
     $currentHeaderName = '';
     foreach ($headerLines as $headerLine) {
         // Line separated
         if (ctype_space($headerLines[0]) || false === strpos($headerLine, ':')) {
             $headers[$currentHeaderName] .= ' ' . trim($headerLine);
             continue;
         }
         $header = explode(':', $headerLine, 2);
         $currentHeaderName = strtolower($header[0]);
         $headers[$currentHeaderName] = trim($header[1]);
     }
     $messageStream = new Swift_ByteStream_TemporaryFileByteStream();
     $messageStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF');
     $messageStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF');
     $messageHeaders = $message->getHeaders();
     // No need to check for 'application/pkcs7-mime', as this is always base64
     if ('multipart/signed;' === substr($headers['content-type'], 0, 17)) {
         if (!preg_match('/boundary=("[^"]+"|(?:[^\\s]+|$))/is', $headers['content-type'], $contentTypeData)) {
             throw new Swift_SwiftException('Failed to find Boundary parameter');
         }
         $boundary = trim($contentTypeData['1'], '"');
         $boundaryLen = strlen($boundary);
         // Skip the header and CRLF CRLF
         $fromStream->setReadPointer($headersPosEnd + 4);
         while (false !== ($buffer = $fromStream->read($bufferLength))) {
             $messageStream->write($buffer);
         }
         $messageStream->commit();
         $messageHeaders->remove('Content-Transfer-Encoding');
         $message->setContentType($headers['content-type']);
         $message->setBoundary($boundary);
         $message->setBody($messageStream);
     } else {
         $fromStream->setReadPointer($headersPosEnd + 4);
         if (null === $this->headerFactory) {
             $this->headerFactory = Swift_DependencyContainer::getInstance()->lookup('mime.headerfactory');
         }
         $message->setContentType($headers['content-type']);
         $messageHeaders->set($this->headerFactory->createTextHeader('Content-Transfer-Encoding', $headers['content-transfer-encoding']));
         $messageHeaders->set($this->headerFactory->createTextHeader('Content-Disposition', $headers['content-disposition']));
         while (false !== ($buffer = $fromStream->read($bufferLength))) {
             $messageStream->write($buffer);
         }
         $messageStream->commit();
         $message->setBody($messageStream);
     }
 }
 protected function _mapToSwift(SendGrid\Email $mail)
 {
     $message = new \Swift_Message($mail->getSubject());
     /*
      * Since we're sending transactional email, we want the message to go to one person at a time, rather
      * than a bulk send on one message. In order to do this, we'll have to send the list of recipients through the headers
      * but Swift still requires a 'to' address. So we'll falsify it with the from address, as it will be 
      * ignored anyway.
      */
     $message->setTo($mail->to);
     $message->setFrom($mail->getFrom(true));
     $message->setCc($mail->getCcs());
     $message->setBcc($mail->getBccs());
     if ($mail->getHtml()) {
         $message->setBody($mail->getHtml(), 'text/html');
         if ($mail->getText()) {
             $message->addPart($mail->getText(), 'text/plain');
         }
     } else {
         $message->setBody($mail->getText(), 'text/plain');
     }
     if ($replyto = $mail->getReplyTo()) {
         $message->setReplyTo($replyto);
     }
     $attachments = $mail->getAttachments();
     //add any attachments that were added
     if ($attachments) {
         foreach ($attachments as $attachment) {
             $message->attach(\Swift_Attachment::fromPath($attachment['file']));
         }
     }
     $message_headers = $message->getHeaders();
     $message_headers->addTextHeader("x-smtpapi", $mail->smtpapi->jsonString());
     return $message;
 }
Ejemplo n.º 24
0
 protected function _mapToSwift(Mail $mail)
 {
     $message = new \Swift_Message($mail->getSubject());
     /*
      * Since we're sending transactional email, we want the message to go to one person at a time, rather
      * than a bulk send on one message. In order to do this, we'll have to send the list of recipients through the headers
      * but Swift still requires a 'to' address. So we'll falsify it with the from address, as it will be 
      * ignored anyway.
      */
     $message->setTo($mail->getFrom());
     $message->setFrom($mail->getFrom(true));
     $message->setCc($mail->getCcs());
     $message->setBcc($mail->getBccs());
     if ($mail->getHtml()) {
         $message->setBody($mail->getHtml(), 'text/html');
         if ($mail->getText()) {
             $message->addPart($mail->getText(), 'text/plain');
         }
     } else {
         $message->setBody($mail->getText(), 'text/plain');
     }
     if ($replyto = $mail->getReplyTo()) {
         $message->setReplyTo($replyto);
     }
     // determine whether or not we can use SMTP recipients (non header based)
     if ($mail->useHeaders()) {
         //send header based email
         $message->setTo($mail->getFrom());
         //here we'll add the recipients list to the headers
         $headers = $mail->getHeaders();
         $headers['to'] = $mail->getTos();
         $mail->setHeaders($headers);
     } else {
         $recipients = array();
         foreach ($mail->getTos() as $recipient) {
             if (preg_match("/(.*)<(.*)>/", $recipient, $results)) {
                 $recipients[trim($results[2])] = trim($results[1]);
             } else {
                 $recipients[] = $recipient;
             }
         }
         $message->setTo($recipients);
     }
     $attachments = $mail->getAttachments();
     //add any attachments that were added
     if ($attachments) {
         foreach ($attachments as $attachment) {
             $message->attach(\Swift_Attachment::fromPath($attachment['file']));
         }
     }
     //add all the headers
     $headers = $message->getHeaders();
     $headers->addTextHeader('X-SMTPAPI', $mail->getHeadersJson());
     return $message;
 }
Ejemplo n.º 25
0
 /**
  * Removes a header from a message.
  *
  * @param \Swift_Message $message
  *                                The message which the header is to be removed from.
  * @param string         $key
  *                                The header key.
  */
 protected static function removeHeader(\Swift_Message $message, $key)
 {
     // Get message headers.
     $headers = $message->getHeaders();
     // Remove the header if it already exists.
     $headers->removeAll($key);
 }
Ejemplo n.º 26
0
 /**
  * Search and replace tokens
  * Adapted from \Swift_Plugins_DecoratorPlugin
  *
  * @param array          $search
  * @param array          $replace
  * @param \Swift_Message $message
  */
 public static function searchReplaceTokens($search, $replace, \Swift_Message &$message)
 {
     // Body
     $body = $message->getBody();
     $bodyReplaced = str_ireplace($search, $replace, $body, $updated);
     if ($updated) {
         $message->setBody($bodyReplaced);
     }
     unset($body, $bodyReplaced);
     // Subject
     $subject = $message->getSubject();
     $bodyReplaced = str_ireplace($search, $replace, $subject, $updated);
     if ($updated) {
         $message->setSubject($bodyReplaced);
     }
     unset($subject, $bodyReplaced);
     // Headers
     /** @var \Swift_Mime_Header $header */
     foreach ($message->getHeaders()->getAll() as $header) {
         $headerBody = $header->getFieldBodyModel();
         $updated = false;
         if (is_array($headerBody)) {
             $bodyReplaced = array();
             foreach ($headerBody as $key => $value) {
                 $count1 = $count2 = 0;
                 $key = is_string($key) ? str_ireplace($search, $replace, $key, $count1) : $key;
                 $value = is_string($value) ? str_ireplace($search, $replace, $value, $count2) : $value;
                 $bodyReplaced[$key] = $value;
                 if ($count1 + $count2) {
                     $updated = true;
                 }
             }
         } else {
             $bodyReplaced = str_ireplace($search, $replace, $headerBody, $updated);
         }
         if (!empty($updated)) {
             $header->setFieldBodyModel($bodyReplaced);
         }
         unset($headerBody, $bodyReplaced);
     }
     // Parts (plaintext)
     $children = (array) $message->getChildren();
     /** @var \Swift_Mime_MimeEntity $child */
     foreach ($children as $child) {
         $childType = $child->getContentType();
         list($type, ) = sscanf($childType, '%[^/]/%s');
         if ($type == 'text') {
             $childBody = $child->getBody();
             $bodyReplaced = str_ireplace($search, $replace, $childBody);
             if ($childBody != $bodyReplaced) {
                 $childBody = strip_tags($bodyReplaced);
                 $child->setBody($childBody);
             }
         }
         unset($childBody, $bodyReplaced);
     }
 }
 /**
  * @Then the email header should contain :header with value :value
  */
 public function theEmailHeaderShouldContainWithValue($header, $value)
 {
     $this->theEmailHeaderShouldContain($header);
     Assert::assertEquals($value, $this->message->getHeaders()->get($header)->getFieldBody());
 }