/**
  * Creates a swift message from a ParsedMessage, handles defaults
  *
  * @param ParsedMessage $parsedMessage
  *
  * @return \Swift_Message
  */
 protected function transformMessage(ParsedMessage $parsedMessage)
 {
     $message = new \Swift_Message();
     if ($from = $parsedMessage->getFrom()) {
         $message->setFrom($from);
     }
     // handle to with defaults
     if ($to = $parsedMessage->getTo()) {
         $message->setTo($to);
     }
     // handle cc with defaults
     if ($cc = $parsedMessage->getCc()) {
         $message->setCc($cc);
     }
     // handle bcc with defaults
     if ($bcc = $parsedMessage->getBcc()) {
         $message->setBcc($bcc);
     }
     // handle reply to with defaults
     if ($replyTo = $parsedMessage->getReplyTo()) {
         $message->setReplyTo($replyTo);
     }
     // handle subject with default
     if ($subject = $parsedMessage->getSubject()) {
         $message->setSubject($subject);
     }
     // handle body, no default values here
     $message->setBody($parsedMessage->getMessageText());
     if ($parsedMessage->getMessageHtml()) {
         $message->addPart($parsedMessage->getMessageHtml(), 'text/html');
     }
     return $message;
 }
 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;
 }
Beispiel #3
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;
 }
Beispiel #4
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);
        }
    }
    /**
     * 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;
    }
Beispiel #6
0
 public function testWritingMessageToByteStreamTwiceUsingAFileAttachment()
 {
     $message = new Swift_Message();
     $message->setSubject('test subject');
     $message->setTo('*****@*****.**');
     $message->setCc('*****@*****.**');
     $message->setFrom('*****@*****.**');
     $attachment = Swift_Attachment::fromPath($this->_attFile);
     $message->attach($attachment);
     $message->setBody('HTML part', 'text/html');
     $id = $message->getId();
     $date = preg_quote(date('r', $message->getDate()), '~');
     $boundary = $message->getBoundary();
     $streamA = new Swift_ByteStream_ArrayByteStream();
     $streamB = new Swift_ByteStream_ArrayByteStream();
     $pattern = '~^' . 'Message-ID: <' . $id . '>' . "\r\n" . 'Date: ' . $date . "\r\n" . 'Subject: test subject' . "\r\n" . 'From: user@domain.tld' . "\r\n" . 'To: user@domain.tld' . "\r\n" . 'Cc: other@domain.tld' . "\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: text/html; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'HTML part' . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: ' . $this->_attFileType . '; name=' . $this->_attFileName . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: attachment; filename=' . $this->_attFileName . "\r\n" . "\r\n" . preg_quote(base64_encode(file_get_contents($this->_attFile)), '~') . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D';
     $message->toByteStream($streamA);
     $message->toByteStream($streamB);
     $this->assertPatternInStream($pattern, $streamA);
     $this->assertPatternInStream($pattern, $streamB);
 }
 /**
  * @param string $template
  * @param array  $data
  *
  * @throws \InvalidArgumentException
  * @return \Swift_Mime_Message
  */
 protected function _createMessage($template, &$data)
 {
     //	Pull out all the message data
     $_to = array_get($data, 'to');
     $_from = array_get($data, 'from');
     $_replyTo = array_get($data, 'reply_to');
     $_cc = array_get($data, 'cc');
     $_bcc = array_get($data, 'bcc');
     $_subject = array_get($data, 'subject');
     //	Get body template...
     if (false === ($_html = @file_get_contents($template))) {
         //	Something went awry
         throw new \InvalidArgumentException('Error reading contents of template "' . $template . '".');
     }
     //	And the message...
     $_message = new \Swift_Message();
     if (!empty($_subject)) {
         $_message->setSubject($_subject);
     }
     if (!empty($_to)) {
         $_message->setTo($_to);
     }
     if (!empty($_from)) {
         $_message->setFrom($_from);
     }
     if (!empty($_cc)) {
         $_message->setCc($_cc);
     }
     if (!empty($_bcc)) {
         $_message->setBcc($_bcc);
     }
     if (!empty($_replyTo)) {
         $_message->setReplyTo($_replyTo);
     }
     //	process generic macros.
     $_message->setBody($this->replaceMacros($data, $_html), 'text/html');
     return $_message;
 }
Beispiel #8
0
 /**
  * Add CC e-mail addresses
  *
  * Friendly name portions (e.g. Admin <*****@*****.**>) are allowed. The
  * method takes an unlimited number of recipient addresses.
  */
 public function sendCc()
 {
     $this->objMessage->setCc($this->compileRecipients(func_get_args()));
 }
 /**
  * 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);
     }
 }
 /**
  * Creating the message Carbon Copy (cc).
  *
  * @return MailInterface The current instance
  */
 protected function buildCc() : MailInterface
 {
     null === $this->get('ccAddresses') ? null : $this->swiftMessage->setCc((array) $this->get('ccAddresses'));
     return $this;
 }
Beispiel #11
0
 public function testSendFailed()
 {
     $serviceManager = new CM_Service_Manager();
     $logger = $this->mockObject('CM_Log_Logger');
     $serviceManager->registerInstance('logger', $logger);
     $transport = $this->mockInterface('Swift_Transport')->newInstance();
     $transport->mockMethod('isStarted')->set(true);
     $message = new Swift_Message('foo', 'content');
     $message->setFrom('*****@*****.**', 'Foobar');
     $message->setTo('*****@*****.**');
     $message->setCc('*****@*****.**', 'bar');
     $client = new CM_Mail_Mailer($transport);
     $client->setServiceManager($serviceManager);
     $sendMethod = $transport->mockMethod('send')->set(0);
     $errorMethod = $logger->mockMethod('error')->set(function ($message, CM_Log_Context $context = null) {
         $this->assertSame('Failed to send email', $message);
         $this->assertSame(['message' => ['subject' => 'foo', 'from' => ['*****@*****.**' => 'Foobar'], 'to' => ['*****@*****.**' => null], 'cc' => ['*****@*****.**' => 'bar'], 'bcc' => null], 'failedRecipients' => ['*****@*****.**', '*****@*****.**']], $context->getExtra());
     });
     $failedRecipients = ['*****@*****.**', '*****@*****.**'];
     $client->send($message, $failedRecipients);
     /** @var CM_Exception_Invalid $exception */
     $this->assertSame(1, $sendMethod->getCallCount());
     $this->assertSame(1, $errorMethod->getCallCount());
 }
Beispiel #12
0
function send_email($to, $from, $cc = '', $bcc = '', $subject, $message, $attachments_arr = '', $plain_message = '', $field_type = "pdf")
{
    LOG_MSG('INFO', "send_email(): START EMAILER_HOST=[" . EMAILER_HOST . "] to=[{$to}] from=[{$from}] cc=[{$cc}] bcc=[{$bcc}] subject=[{$subject}]");
    // Defaults
    $EOL = PHP_EOL;
    $separator = md5(time());
    if (!$bcc) {
        $bcc = EMAIL_BCC;
    }
    // Copy of the message without the attachment details
    // required to insert into the db
    if ($plain_message == '') {
        $plain_message = $message;
    }
    $plain_subject = $subject;
    // The subject should have the shop domain
    if (defined('SHOP_NAME')) {
        $subject = "[" . SHOP_NAME . "] {$subject}";
    } else {
        $subject = "[" . SITE_NAME . "] {$subject}";
    }
    // common headers
    $headers = "From: {$from} {$EOL}";
    $headers .= "CC: {$cc} {$EOL}";
    $headers .= "Bcc: {$bcc} {$EOL}";
    if ($attachments_arr) {
        // main header
        $headers .= "MIME-Version: 1.0" . $EOL;
        $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"";
        // body
        //$body = "--".$separator.$EOL;
        $body = "Content-Transfer-Encoding: 7bit" . $EOL . $EOL;
        $body .= "--" . $separator . $EOL;
        $body .= "Content-Type: text/html; charset=\"iso-8859-1\"" . $EOL;
        $body .= "Content-Transfer-Encoding: 8bit" . $EOL . $EOL;
        $body .= $message . $EOL;
        // attachment
        $attachment = chunk_split(base64_encode($attachments_arr[0]['data']));
        $body .= "--" . $separator . $EOL;
        $body .= "Content-Type: application/octet-stream; name=\"" . $attachments_arr[0]['filename'] . "\"" . $EOL;
        $body .= "Content-Transfer-Encoding: base64" . $EOL;
        $body .= "Content-Disposition: attachment" . $EOL . $EOL;
        $body .= $attachment . $EOL;
        $body .= "--" . $separator . "--";
        $message = $body;
    } else {
        $headers .= "Content-Type: text/html {$EOL}";
        $headers .= "MIME-Version: 1.0 {$EOL}";
        //$headers.="charset=utf-8 $EOL";
        $headers .= "Content-Transfer-Encoding: 8bit {$EOL}";
        $headers .= "X-Mailer: Shopnix - eCommerce Solution {$EOL}";
    }
    // Setup parameters
    $status = 'SUCCESS';
    if (EMAILER_HOST == 'LOCAL') {
        $emailer_host = $_SERVER['SERVER_NAME'];
        $resp = mail($to, $subject, $message, $headers);
        // SEND EMAIL
        if ($resp) {
            $status = 'SUCCESS';
        } else {
            $status = 'FAILED';
        }
    } elseif (EMAILER_HOST == 'REMOTE') {
        $headers .= "From:{$from} \nCC: {$cc} \nBcc: {$bcc}";
        $from = urlencode($from);
        $to = urlencode($to);
        $cc = urlencode($cc);
        $bcc = urlencode($bcc);
        $subject = urlencode($subject);
        $url = "http://mitnix.in/snix/modules/utils/emailer.php?to={$to}&from={$from}&cc={$cc}&bcc={$bcc}&sub={$subject}";
        $resp = curl_post($url, $message);
        // SEND EMAIL
        $emailer_host = 'cloudnix.com';
    } elseif (EMAILER_HOST == 'MANDRILL') {
        // Setup data
        $sw_from = convert_email($from);
        $sw_to = convert_email($to);
        $text = strip_tags($plain_message);
        $html = $plain_message;
        $emailer_host = 'Mandrill';
        // Setup connection info
        $transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
        $transport->setUsername(SMTP_USERNAME);
        $transport->setPassword(SMTP_PASSWORD);
        $swift = Swift_Mailer::newInstance($transport);
        // Setup Data object
        $message = new Swift_Message($subject);
        $message->setFrom($sw_from);
        $message->setBody($html, 'text/html');
        $message->setTo($sw_to);
        $message->addPart($text, 'text/plain');
        if ($bcc) {
            $sw_bcc = convert_email($bcc);
            //echo "<pre>Setting BCC[$bcc] to [".print_r($sw_bcc,true)."]</pre>";
            $message->setBcc($sw_bcc);
        }
        if ($cc) {
            $sw_cc = convert_email($cc);
            //echo "<pre>Setting CC[$cc] to [".print_r($sw_cc,true)."]</pre>";
            $message->setCc($sw_cc);
        }
        if ($attachments_arr) {
            // Create the attachment with your data
            $attachment = Swift_Attachment::newInstance($attachments_arr[0]['data'], $attachments_arr[0]['filename'], "application/{$field_type}");
            // Attach it to the message
            $message->attach($attachment);
        }
        // Send mail
        if ($recipients = $swift->send($message, $failures)) {
            $resp = true;
            $status = 'SUCCESS';
        } else {
            LOG_MSG('ERROR', "send_email(MANDRILL): Error sending email=[" . print_r($failures, true) . "]");
            $resp = false;
            $status = 'FAILED';
        }
    } else {
        LOG_MSG("INFO", "EMAILER_HOST is OFF. Not sending email");
        $status = 'NOT SENT';
        $resp = true;
    }
    if (defined('SHOP_ID') && $from != '*****@*****.**') {
        // Don't store security emails
        $email_resp = db_emails_insert($from, $to, $cc, $bcc, $plain_subject, $plain_message, $status, $headers, $emailer_host);
        if ($email_resp['STATUS'] != 'OK') {
            LOG_MSG('ERROR', "send_email(): Error while inserting in EMails talble from=[{$from}] to=[{$to}]");
        }
    }
    LOG_MSG("INFO", "\n\t******************************EMAIL START [{$status}]******************************\n\tTO: [{$to}]\n\t{$headers}\n\tSUBJECT:[{$subject}]\n\t{$plain_message}\n\t******************************EMAIL END******************************");
    return $resp;
}
Beispiel #13
0
 /**
  * {@inheritdoc}
  *
  * @return $this|self
  */
 public function setCc($addresses, $name = null) : self
 {
     $this->message->setCc($addresses, $name);
     return $this;
 }
Beispiel #14
0
function send_email($to, $from, $cc = '', $bcc = '', $subject, $message)
{
    LOG_MSG('INFO', "send_email(): START EMAILER_HOST=[" . EMAILER_HOST . "] to=[{$to}] from=[{$from}] cc=[{$cc}] bcc=[{$bcc}] subject=[{$subject}]");
    // Defaults
    if (!$bcc) {
        $bcc = EMAIL_BCC;
    }
    // Add footer to the message
    ob_start();
    include HTML_DIR . '/emails/email_footer.html';
    $message .= ob_get_contents();
    ob_get_clean();
    $headers = "Content-Type: text/html\r\n";
    //."MIME-Version: 1.0\r\n"
    //."charset=utf-8\r\n"
    //."Content-Transfer-Encoding: 8bit\r\n"
    //."X-Mailer: Shopnix - eCommerce Solution\r\n";
    // To store subject whithout appending with SHOP_NAME
    $plain_subject = $subject;
    $subject = "[" . SHOP_NAME . "] {$subject}";
    // Setup parameters
    $status = 'SUCCESS';
    if (EMAILER_HOST == 'LOCAL') {
        $emailer_host = $_SERVER['SERVER_NAME'];
        $headers .= "From: {$from}\r\n";
        $headers .= "CC: {$cc}\r\n";
        $headers .= "Bcc: {$bcc}\r\n";
        $resp = mail($to, $subject, $message, $headers);
        // SEND EMAIL
        if ($resp) {
            $status = 'SUCCESS';
        } else {
            $status = 'FAILED';
        }
    } elseif (EMAILER_HOST == 'REMOTE') {
        $headers .= "From:{$from} \nCC: {$cc} \nBcc: {$bcc}";
        $from = urlencode($from);
        $to = urlencode($to);
        $cc = urlencode($cc);
        $bcc = urlencode($bcc);
        $subject = urlencode($subject);
        $url = "";
        $resp = curl_post($url, $message);
        // SEND EMAIL
        $emailer_host = 'cloudnix.com';
    } elseif (EMAILER_HOST == 'MANDRILL') {
        // Setup data
        $sw_from = convert_email($from);
        $sw_to = convert_email($to);
        $text = strip_tags($message);
        $html = $message;
        $emailer_host = 'Mandrill';
        // Setup connection info
        $transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com1', 587);
        $transport->setUsername(SMTP_USERNAME);
        $transport->setPassword(SMTP_PASSWORD);
        $swift = Swift_Mailer::newInstance($transport);
        // Setup Data object
        $sw_message = new Swift_Message($subject);
        $sw_message->setFrom($sw_from);
        $sw_message->setBody($html, 'text/html');
        $sw_message->setTo($sw_to);
        $sw_message->addPart($text, 'text/plain');
        if ($bcc) {
            $sw_bcc = convert_email($bcc);
            //echo "<pre>Setting BCC[$bcc] to [".print_r($sw_bcc,true)."]</pre>";
            $sw_message->setBcc($sw_bcc);
        }
        if ($cc) {
            $sw_cc = convert_email($cc);
            //echo "<pre>Setting CC[$cc] to [".print_r($sw_cc,true)."]</pre>";
            $sw_message->setCc($sw_cc);
        }
        // Send mail
        if ($recipients = $swift->send($sw_message, $failures)) {
            $resp = true;
            $status = 'SUCCESS';
        } else {
            LOG_MSG('ERROR', "send_email(MANDRILL): Error sending email=[" . print_r($failures, true) . "]");
            $resp = false;
            $status = 'FAILED';
        }
    } else {
        LOG_MSG("INFO", "EMAILER_HOST is OFF. Not sending email");
        $status = 'NOT SENT';
        $resp = true;
    }
    $email_resp = db_emails_insert($from, $to, $cc, $bcc, $plain_subject, $message, $status, $headers, EMAILER_HOST);
    if ($email_resp['STATUS'] != 'OK') {
        LOG_MSG('ERROR', "send_email(): Error while inserting in EMails talble from=[{$from}] to=[{$to}]");
    }
    LOG_MSG("INFO", "\n\t******************************EMAIL START[{$status}]******************************\n\tTO: [{$to}]\n\t{$headers}\n\tSUBJECT:[{$subject}]\n\t{$message}\n\t******************************EMAIL END******************************");
    return $resp;
}
 /**
  * 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;
 }
Beispiel #16
0
 /**
  *
  * {@inheritDoc}
  *
  * @see \API\Component\Mail\MailInterface::sendRaw()
  */
 public function sendRaw($from, $to, $subject, $body, $cc = null, $attachment = null)
 {
     if (!is_array($from)) {
         $from = [$from];
     }
     if (!is_array($to)) {
         $to = [$to];
     }
     $message = new Message();
     $message->setSubject($subject);
     $message->setFrom($from);
     $message->setTo($to);
     $message->setBody($body, 'text/html');
     if ($cc != null) {
         $message->setCc($cc);
     }
     if ($attachment instanceof Attachment) {
         $message->attach($attachment);
     }
     return $this->_mailer->send($message, $this->_failedRecipients);
 }
Beispiel #17
0
 /**
  * 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;
 }
Beispiel #18
0
 /**
  * Set the Cc addresses of this message.
  *
  * If $name is passed and the first parameter is a string, this name will be
  * associated with the address.
  *
  * @param string|array $addresses
  * @param string $name optional
  * @return \TYPO3\CMS\Core\Mail\MailMessage
  */
 public function setCc($addresses, $name = null)
 {
     $addresses = $this->idnaEncodeAddresses($addresses);
     return parent::setCc($addresses, $name);
 }