/**
 * emailNotification()
 * creates an email message with the pdf and sends it
 * 
 * @param		string			pdf binary/string stream
 * @param		array			customer information array
 * @param		array			smtp server information
 * @param		string			from email address of the sender identity
 */
function emailNotification($pdfDocument, $customerInfo, $smtpInfo, $from)
{
    global $base;
    if (empty($customerInfo['business_email'])) {
        return;
    }
    $headers = array("From" => $from, "Subject" => "User Invoice Notification", "Reply-To" => $from);
    $mime = new Mail_mime();
    $mime->setTXTBody("Notification letter of service");
    $mime->addAttachment($pdfDocument, "application/pdf", "invoice.pdf", false, 'base64');
    $body = $mime->get();
    $headers = $mime->headers($headers);
    $mail =& Mail::factory("smtp", $smtpInfo);
    $mail->send($customerInfo['business_email'], $headers, $body);
}
Esempio n. 2
1
 private function send_email($to, $subject, $body, $attachments)
 {
     require_once 'Mail.php';
     require_once 'Mail/mime.php';
     require_once 'Mail/mail.php';
     $headers = array('From' => _EMAIL_ADDRESS, 'To' => $to, 'Subject' => $subject);
     // attachment
     $crlf = "\n";
     $mime = new Mail_mime($crlf);
     $mime->setHTMLBody($body);
     //$mime->addAttachment($attachment, 'text/plain');
     if (is_array($attachments)) {
         foreach ($attachments as $attachment) {
             $mime->addAttachment($attachment, 'text/plain');
         }
     }
     $body = $mime->get();
     $headers = $mime->headers($headers);
     $smtp = Mail::factory('smtp', array('host' => _EMAIL_SERVER, 'auth' => true, 'username' => _EMAIL_USER, 'password' => _EMAIL_PASSWORD));
     $mail = $smtp->send($to, $headers, $body);
     if (PEAR::isError($mail)) {
         echo "<p>" . $mail->getMessage() . "</p>";
     } else {
         echo "<p>Message successfully sent!</p>";
     }
 }
Esempio n. 3
1
 function sendEmail()
 {
     foreach ($this->to as $to) {
         $headers = array('From' => SMTP_FROM_NAME . "<" . SMTP_FROM . ">", 'To' => $to, 'Subject' => $this->subject);
         $mime = new Mail_mime($this->NEW_LINE);
         if ($this->body == null) {
             if ($this->compiledTXT != null && strlen($this->compiledTXT) > 0) {
                 $mime->setTXTBody($this->compiledTXT);
             }
             if ($this->compiledHTML != null && strlen($this->compiledHTML) > 0) {
                 $mime->setHTMLBody($this->compiledHTML);
             }
         } else {
             $mime->setTXTBody($this->body);
         }
         foreach ($this->cc as $email) {
             $mime->addCc($email);
         }
         foreach ($this->bcc as $email) {
             $mime->addBcc($email);
         }
         if (is_array($this->files) && count($this->files) > 0) {
             foreach ($this->files as $file) {
                 $mime->addAttachment($file["path"], $file["content-type"]);
             }
         }
         $body = $mime->get();
         $headers = $mime->headers($headers);
         $string = "";
         foreach ($headers as $key => $value) {
             $string .= "{$key}: {$value}\r\n";
         }
         $smtpOptions = array('host' => SMTP_HOST, 'port' => SMTP_PORT);
         if (defined("SMTP_USER_NAME") && defined("SMTP_PASSWORD")) {
             $smtpOptions['auth'] = true;
             $smtpOptions['username'] = SMTP_USER_NAME;
             $smtpOptions['password'] = SMTP_PASSWORD;
         }
         /** @noinspection PhpDynamicAsStaticMethodCallInspection */
         $smtp = Mail::factory('smtp', $smtpOptions);
         $success = $smtp->send($to, $headers, $body);
         if ($success !== true) {
             throw new PEARErrorException($success);
         }
     }
 }
Esempio n. 4
0
function sendMail($absender_email, $absender_name, $Empfaenger, $Betreff, $content, $attachments)
{
    global $config;
    $crlf = "\n";
    $from = "{$absender_name} <{$absender_email}>";
    $headers = array('From' => $from, 'To' => $Empfaenger, 'Subject' => $Betreff);
    $mime = new Mail_mime(array('eol' => $crlf));
    $mime->setTXTBody($content);
    if (isset($attachments)) {
        foreach ($attachments as $attachment) {
            if (isset($attachment["filename"]) && $attachment["filename"] != "" && isset($attachment["mailname"]) && $attachment["mailname"] != "") {
                $mime->addAttachment($attachment["filename"], 'application/octet-stream', $attachment["mailname"], true, 'base64');
            }
        }
    }
    $body = $mime->get(array('html_charset' => 'utf-8', 'text_charset' => 'utf-8', 'eol' => $crlf));
    $hdrs = $mime->headers($headers);
    $smtp = Mail::factory('smtp', array('host' => $config['smtphost'], 'auth' => true, 'username' => $config['smtpusername'], 'password' => $config['smtppassword']));
    $mail = $smtp->send($Empfaenger, $hdrs, $body);
    /*
    if (PEAR::isError($mail)) {
    echo("<p>" . $mail->getMessage() . "</p>");
    } else {
    echo("<p>Message successfully sent!</p>");
    }
    */
    //	mail($Empfaenger, $Betreff, $text, $Header) or die('Die Email
    //	konnte nicht versendet werden');
}
Esempio n. 5
0
 public function main()
 {
     if (empty($this->from)) {
         throw new BuildException('Missing "from" attribute');
     }
     $this->log('Sending mail to ' . $this->tolist);
     if (!empty($this->filesets)) {
         @(require_once 'Mail.php');
         @(require_once 'Mail/mime.php');
         if (!class_exists('Mail_mime')) {
             throw new BuildException('Need the PEAR Mail_mime package to send attachments');
         }
         $mime = new Mail_mime(array('text_charset' => 'UTF-8'));
         $hdrs = array('From' => $this->from, 'Subject' => $this->subject);
         $mime->setTXTBody($this->msg);
         foreach ($this->filesets as $fs) {
             $ds = $fs->getDirectoryScanner($this->project);
             $fromDir = $fs->getDir($this->project);
             $srcFiles = $ds->getIncludedFiles();
             foreach ($srcFiles as $file) {
                 $mime->addAttachment($fromDir . DIRECTORY_SEPARATOR . $file, 'application/octet-stream');
             }
         }
         $body = $mime->get();
         $hdrs = $mime->headers($hdrs);
         $mail = Mail::factory('mail');
         $mail->send($this->tolist, $hdrs, $body);
     } else {
         mail($this->tolist, $this->subject, $this->msg, "From: {$this->from}\n");
     }
 }
Esempio n. 6
0
 function eMail($row, $user = '')
 {
     $lastRun = $this->getLastReportRun($row['subscription_name']);
     $html = $lastRun['report_html'];
     if ($html == '' || $html == 'NULL') {
         return FALSE;
     }
     // Remove google chart data
     $css = file_get_contents('/var/www/html/css/mail.css');
     $message = "<html>\n<head>\n<style>\n{$css}\n</style>\n</head>\n";
     $html = str_replace("<td class='chart'>", "<td>", $html);
     $sp1 = strpos($html, "<body>");
     $sp2 = strpos($html, "<form");
     $sp3 = strpos($html, "</form>");
     $message .= substr($html, $sp1, $sp2 - $sp1);
     $message .= "<p><a href='https://analytics.atari.com/report_log.php?_report=" . $row['subscription_name'] . "&_cache=" . $lastRun['report_startts'] . "'>View This In A Browser</a></p>";
     $message .= substr($html, $sp3 + strlen('</form>'));
     // Now Email the results
     $crlf = "\n";
     $hdrs = array('Subject' => "Atari Analytics: Report: " . $row['subscription_title'] . ". Run completed successfully at " . $lastRun['report_endts'] . ".");
     $mime = new Mail_mime(array('eol' => $crlf));
     $mime->setHTMLBody($message);
     $mime->addAttachment("/tmp/" . $lastRun['report_csv'], 'text/plain');
     $body = $mime->get();
     $hdrs = $mime->headers($hdrs);
     $mail =& Mail::factory('mail');
     if ($user == '') {
         $mail->send($row['subscription_list'], $hdrs, $body);
     } else {
         $mail->send($user, $hdrs, $body);
     }
     return TRUE;
 }
Esempio n. 7
0
 protected function send($alternateRecipient = null)
 {
     $mime = new Mail_mime(array("head_charset" => "utf-8", "text_charset" => "utf-8", "html_charset" => "utf-8", 'eol' => "\n"));
     $mime->setTXTBody($this->txtBody);
     if ($this->htmlBody !== null) {
         $mime->setHTMLBody($this->htmlBody);
     }
     if (!empty($this->attachments)) {
         foreach ($this->attachments as $attachment) {
             $mime->addAttachment($attachment->File(), $attachment->Type());
         }
     }
     $this->headers['To'] = $this->receipients;
     $this->headers['Sender'] = $this->headers['From'];
     $empfaenger = $this->receipients;
     if ($this->bcc !== null) {
         $this->receipients .= ($this->receipients > '' ? ',' : '') . $this->bcc;
     }
     //do not ever try to call these lines in reverse order
     $body = $mime->get();
     $headers = $mime->headers($this->headers, true);
     if ($this->receipients > '') {
         if (!$GLOBALS['Settings']['OnServer']) {
             $this->receipients = '*****@*****.**';
         } elseif ($alternateRecipient) {
             $this->receipients = $alternateRecipient;
         }
         $mail_queue = new Mail_Queue($GLOBALS['Settings']['MailQueue']['db_options'], $GLOBALS['Settings']['MailQueue']['mail_options']);
         $mail_queue->put($this->headers['From'], $this->receipients, $headers, $body, $this->delay);
     }
     return true;
 }
Esempio n. 8
0
function mymail_attach($to, $subject, $body, $attach, $attachdata)
{
    if (!count($attach) && !count($attachdata)) {
        return mymail($to, $subject, $body);
    }
    require_once "Mail/mime.php";
    $json = json_decode(file_get_contents("/home/abhishek/Desktop/GenApp/abhishektest/appconfig.json"));
    $headers = array('From' => 'abhishektest@' . $json->mail->from, 'To' => $to, 'Subject' => $subject);
    $mime = new Mail_mime(array('eol' => "\n"));
    $mime->setTXTBody($body);
    if (count($attachdata)) {
        ob_start();
        foreach ($attach as $f) {
            if (!$mime->addAttachment($f, 'text/plain')) {
                $mime->addAttachment("could not attach {$f}", 'text/plain', "error-{$f}", false);
            }
        }
        ob_end_clean();
    }
    if (count($attachdata)) {
        ob_start();
        foreach ($attachdata as $d) {
            if (isset($d['data']) && isset($d['name'])) {
                if (!$mime->addAttachment($d['data'], 'text/plain', $d['name'], false)) {
                    $mime->addAttachment("could not attach data", 'text/plain', $d['name'], false);
                }
            } else {
                $mime->addAttachment("data data or name not set", 'text/plain', "unknown", false);
            }
        }
        ob_end_clean();
    }
    $body = $mime->get();
    $headers = $mime->headers($headers);
    if (isset($json->mail->smtp)) {
        $smtp = Mail::factory('smtp', array('host' => $json->mail->smtp->host, 'auth' => true, 'username' => $json->mail->smtp->user, 'password' => rtrim(base64_decode($json->mail->smtp->password))));
        $mail = $smtp->send($to, $headers, $body);
        return PEAR::isError($mail);
    }
    $phpmail = Mail::factory('mail');
    $mail = $phpmail->send($to, $headers, $body);
    return PEAR::isError($mail);
}
Esempio n. 9
0
 /**
  * Sends an email
  * 
  * @param array $attachment_files an array containing files to be attached with email.
  * @param string $from the sender of the email.
  * @param string $to the reciever of the email.
  * @param string $subject the subject of the email.
  * @param string $message the message of the email.			 			  			  					 
  * @throws Exception throws an exception if the file size is greater than a limit or the file extension is not valid or the uploaded file could not be copied
  * 
  * @return boolean $is_sent used to indicate if the email was sent.
  */
 public function SendEmail($attachment_files, $from, $to, $subject, $text)
 {
     try {
         /** The email text is encoded */
         $processed = htmlentities($text);
         /** If the encoded text is same as the original text then the text is considered to be plain text */
         if ($processed == $text) {
             $is_html = false;
         } else {
             $is_html = true;
         }
         /** If the attachment files were given */
         if (is_array($attachment_files)) {
             /** Mail_mine object is created */
             $message = new \Mail_mime();
             /** If the message is not html */
             if (!$is_html) {
                 $message->setTXTBody($text);
             } else {
                 $message->setHTMLBody($text);
             }
             /** Each given file is attached */
             for ($count = 0; $count < count($attachment_files); $count++) {
                 $path_of_uploaded_file = $attachment_files[$count];
                 if ($path_of_uploaded_file != "") {
                     $message->addAttachment($path_of_uploaded_file);
                 }
             }
             /** The message body is fetched */
             $body = $message->get();
             /** The extra headers */
             $extraheaders = array("From" => $from, "Subject" => $subject, "Reply-To" => $from);
             /** The email headers */
             $headers = $message->headers($extraheaders);
         } else {
             /** The message body */
             $body = $text;
             /** The message headers */
             $headers = array("From" => $from, "Subject" => $subject, "Reply-To" => $from);
         }
         /** The Mail class object is created */
         $mail = new \Mail("mail");
         /** The email is sent */
         $is_sent = $mail->send($to, $headers, $body);
         if (!$is_sent) {
             throw new \Exception("Email could not be sent. Details: " . $e->getMessage());
         } else {
             return true;
         }
     } catch (\Exception $e) {
         throw new \Exception("Email could not be sent. Details: " . $e->getMessage());
     }
 }
Esempio n. 10
0
 public function send($to, $subject, $body, $type = null, $headers = null, $attachments = null)
 {
     if (is_null($type)) {
         $type = 'text';
     }
     if (is_null($headers)) {
         $headers = array();
     }
     $to = str_replace(';', ',', $to);
     if (!isset($headers['From'])) {
         $headers['From'] = $this->getConf('default_from');
     }
     if (!isset($headers['To'])) {
         $headers['To'] = $to;
     }
     $headers['Subject'] = $subject;
     $required_headers = array('From', 'Subject');
     foreach ($required_headers as $field) {
         if (!@$headers[$field]) {
             throw new Exception("Must have a '{$field}' header.");
         }
     }
     // start
     $mime = new Mail_mime("\n");
     switch ($type) {
         case 'text':
             $mime->setTXTBody($body);
             break;
         case 'html':
             $mime->setHTMLBody($body);
             break;
     }
     if (is_array($attachments)) {
         $defaults = array('type' => 'application/octet-stream', 'name' => '', 'isfile' => true, 'encoding' => 'base64');
         foreach ($attachments as $attachment) {
             if (!isset($attachment['file'])) {
                 throw new Exception("Attachment missing 'file' field.");
             }
             $a = array_merge($defaults, $attachment);
             $res = $mime->addAttachment($a['file'], $a['type'], $a['name'], $a['isfile'], $a['encoding']);
         }
     }
     // order is important
     $b = $mime->get();
     $h = $mime->headers($headers);
     $res = $this->mail->send($to, $h, $b);
     if (PEAR::isError($res)) {
         throw new Exception('Could not send email (' . $res->getMessage() . ' - ' . $res->getUserinfo() . ')');
     }
 }
Esempio n. 11
0
File: Mailer.php Progetto: hlag/svs
    function sendMail($to, $subject, $mailText, $from = "", $type = "", $prozess = 1)
    {
        Logger::getInstance()->Log($to, LOG_ABLAUF);

        $message = new Mail_mime("\n");
        // watt isn dat hier für ne funktion? die macht mit sicherheit alles, aber keinen html-Body
        $message->setHTMLBody($mailText);
        if ($this->attachement != null)
        {
            foreach ($this->attachement AS $attachment)
                $messageatt = $message->addAttachment($attachment);
            //Logger::getInstance()->Log($messageatt,LOG_ABLAUF);
            $this->attachement = null;
        }

        if (empty($from))
            $header['From'] = $this->from;
        else
            $header['From'] = $from;
        $header['Subject'] = $subject;
        $header['To'] = $to;
        $header['Date'] = date("D, d M Y H:i:s O");
        $header['Message-ID'] = '<' . time() . '.' . $prozess . '@' . $this->host . '>';


        $messBody = $message->get(array("text_encoding" => "quoted-printable"));
        if ($type == 'html')
            $messBody = '<html><body>' . $messBody . '</body></html>';

        $header2 = $message->headers($header);

        $error_obj = self::$mailer->send($to, $header2, $messBody);


        if (is_object($error_obj))
        {
            //Logger::getInstance()->Log($message, LOG_ABLAUF);
            $errorString = ob_get_contents();
            file_put_contents(PATH . 'mail.error.log', $errorString);
            return false;
        }
        else
        {


            //z('email was send successfully!');
            return true;
        }
    }
/**
 * sendWelcomeNotification()
 * wrapper-function to send notification to the customer
 * 
 * @param		array			customer information array
 * @param		array			smtp server information
 * @param		string			from email address of the sender identity
 */
function sendWelcomeNotification($customerInfo, $smtpInfo, $from)
{
    global $base;
    if (empty($customerInfo['customer_email'])) {
        return;
    }
    $headers = array("From" => $from, "Subject" => "Welcome new customer!", "Reply-To" => $from);
    $html = prepareNotificationTemplate($customerInfo);
    $pdfDocument = createPDF($html);
    $mime = new Mail_mime();
    $mime->setTXTBody("Notification letter of service");
    $mime->addAttachment($pdfDocument, "application/pdf", "notification.pdf", false, 'base64');
    $body = $mime->get();
    $headers = $mime->headers($headers);
    $mail =& Mail::factory("smtp", $smtpInfo);
    $mail->send($customerInfo['customer_email'], $headers, $body);
}
Esempio n. 13
0
 /**
  * Método que envía el correo
  * @return Arreglo con los estados de retorno por cada correo enviado
  * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl)
  * @version 2016-05-12
  */
 public function send()
 {
     // Crear correo
     $mailer = \Mail::factory('smtp', $this->_config);
     $mail = new \Mail_mime();
     // Asignar mensaje
     $mail->setTXTBody($this->_data['text']);
     $mail->setHTMLBody($this->_data['html']);
     // Si existen archivos adjuntos agregarlos
     if (!empty($this->_data['attach'])) {
         foreach ($this->_data['attach'] as &$file) {
             $result = $mail->addAttachment(isset($file['tmp_name']) ? $file['tmp_name'] : $file['data'], $file['type'], $file['name'], isset($file['tmp_name']) ? true : false);
             if (is_a($result, 'PEAR_Error')) {
                 return ['type' => $result->getType(), 'code' => $result->getCode(), 'message' => $result->getMessage()];
             }
         }
     }
     // cuerpo y cabecera con codificación en UTF-8
     $body = $mail->get(['text_encoding' => '8bit', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8', 'head_charset' => 'UTF-8', 'head_encoding' => '8bit']);
     // debe llamarse antes de headers
     $to = implode(', ', $this->_header['to']);
     $headers_data = ['From' => $this->_header['from'], 'To' => $to, 'Subject' => $this->_header['subject']];
     if (!empty($this->_header['cc'])) {
         $headers_data['Cc'] = implode(', ', $this->_header['cc']);
     }
     if (!empty($this->_header['replyTo'])) {
         //$headers_data['Reply-To'] = $headers_data['Return-Path'] = $this->_header['replyTo'];
         $headers_data['Reply-To'] = $this->_header['replyTo'];
     }
     $headers = $mail->headers($headers_data);
     if (!empty($this->_header['cc'])) {
         $to .= ', ' . implode(', ', $this->_header['cc']);
     }
     if (!empty($this->_header['bcc'])) {
         $to .= ', ' . implode(', ', $this->_header['bcc']);
     }
     // Enviar correo a todos los destinatarios
     $result = $mailer->send($to, $headers, $body);
     // retornar estado del envío del mensaje
     if (is_a($result, 'PEAR_Error')) {
         return ['type' => $result->getType(), 'code' => $result->getCode(), 'message' => $result->getMessage()];
     } else {
         return true;
     }
 }
Esempio n. 14
0
 public function sendEmail($sSubject, $sReceipients, $sFrom, $sBody, $sAttachmentPath = null)
 {
     $text = strip_tags($sBody);
     $html = $sBody;
     if ($sAttachmentPath != null) {
         $file = $sAttachmentPath;
     }
     $crlf = "\n";
     $hdrs = array('From' => $sFrom, 'Subject' => $sSubject);
     $mime = new Mail_mime(array('eol' => $crlf));
     $mime->setTXTBody($text);
     $mime->setHTMLBody($html);
     $mime->addAttachment($file, 'text/plain');
     $body = $mime->get();
     $hdrs = $mime->headers($hdrs);
     $mail =& Mail::factory('mail');
     $mail->send($sReceipients, $hdrs, $body);
 }
Esempio n. 15
0
function generate_xml_email_kb_main_debug($firstName, $lastName, $email, $phone, $comment)
{
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    //    if ($_SERVER['HTTP_HOST'] !== 'www.inspirada.com') return;
    require_once "Mail.php";
    require_once "Mail/mime.php";
    $to = '*****@*****.**';
    $xml = '<?xml version="1.0" encoding="UTF-8" ?>';
    $xml .= '<hsleads>' . PHP_EOL;
    $xml .= '<lead>' . PHP_EOL;
    $xml .= '<submit_date_time>' . str_replace('+00:00', '', date('c', strtotime('now'))) . '</submit_date_time>' . PHP_EOL;
    $xml .= '<firstname>' . substr($firstName, 0, 15) . '</firstname>' . PHP_EOL;
    $xml .= '<lastname>' . substr($lastName, 0, 40) . '</lastname>' . PHP_EOL;
    $xml .= '<email>' . substr($email, 0, 40) . '</email>' . PHP_EOL;
    $xml .= '<phone>' . substr(preg_replace("/[^0-9]/", "", $phone), 0, 10) . '</phone>' . PHP_EOL;
    $xml .= '<message>' . substr($comment, 0, 2048) . '</message>' . PHP_EOL;
    $xml .= '<buildernumber>00850</buildernumber>' . PHP_EOL;
    $xml .= '<builderreportingname>Las Vegas</builderreportingname>' . PHP_EOL;
    $xml .= '<communitynumber></communitynumber>' . PHP_EOL;
    $xml .= '</lead>' . PHP_EOL;
    $xml .= '</hsleads>';
    $from = "Inspirada <*****@*****.**>";
    $subject = "Inspirada - Henderson - Info Requested";
    $host = "smtp.gmail.com";
    $port = '465';
    $username = "******";
    $password = "******";
    $headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);
    // Format Message
    $body = '';
    $mime = new Mail_mime();
    $mime->setHTMLBody($body);
    $xmlobj = new SimpleXMLElement($xml);
    $xmlobj->asXML(ABSPATH . 'wp-content/plugins/property-finder/public/export/' . time() . '.xml');
    $mime->addAttachment(ABSPATH . 'wp-content/plugins/property-finder/public/export/' . time() . '.xml', 'text/xml');
    $body = $mime->get();
    $headers = $mime->headers($headers);
    $smtp = Mail::factory('smtp', array('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password));
    $mail = $smtp->send($to, $headers, $body);
    return PEAR::isError($mail) ? false : true;
}
Esempio n. 16
0
function sendEmail($recipientData, $pdfFile, $date, $senderName)
{
    $recipientName = $recipientData["name"];
    $recipientMail = $recipientData["email"];
    $recipientHashUn = $recipientData["hash_unsubscribe"];
    $message = "Dear .{$recipientName}.\n\nyour Hotcat report for " . $date . " has arrived!\n\nThe attached PDF file contains the most recent SSL/TLS scanning results, aggregated just for you (and all the other subscribers).\n\nIn case you are interested in more detailed results and other awesome stuff, please visit: " . "https://hotcat.de \n\n" . "If you are, on the other hand, not interested any more in receiving Hotcat reports, please use the following link in order to cancel your subscription:\n\nhttps://hotcat.de/php/unsubscribe.php?email=" . $recipientMail . "&hash_unsubscribe=" . $recipientHashUn . "\n\nPlease be advised that we kill a really cute baby kitten for every user that unsubscribes. Anyway, thanks for your subscription and have a lovely day!\n With hot regards\n\n " . $senderName;
    $subject = "Your monthly Hotcat report";
    $mime = new Mail_mime();
    $mime->setTXTBody($message);
    $mime->addAttachment($pdfFile, "Application/pdf");
    $body = $mime->get();
    $header = $mime->headers(array('To' => $recipientMail, 'Subject' => $subject));
    $mail =& Mail::factory('mail');
    $mail->send($recipientMail, $header, $body);
    //errors
    if (PEAR::isError($mail)) {
        echo "<p>" . $mail->getMessage() . "<p>";
    } else {
        echo "Message sent successfully to " . $recipientMail . "!\n";
    }
    sleep(5);
}
function sendEmail($mailhost, $mailusername, $mailpassword, $mailport, $recipient, $subject, $body, $filename)
{
    echo "reached mail function" . "\n";
    $message = new Mail_mime();
    $text = $body;
    echo "creating mail object" . "\n";
    $message->setTXTBody($text);
    //$message->setHTMLBody($html);
    if ($filename != null) {
        $message->addAttachment($filename);
    }
    $messagebody = $message->get();
    echo "further along" . "\n";
    $extraheaders = array("From" => $mailusername, "Subject" => $subject);
    $headers = $message->headers($extraheaders);
    echo "attached headers to message" . "\n";
    $mail = Mail::factory("mail");
    echo "factory\n";
    print_r($mail);
    $mail->send($recipient, $headers, $messagebody);
    echo "sent message";
}
Esempio n. 18
0
 /**
  * Sends an email
  *
  * @since 1.0.0	
  * @param array $attachment_files an array containing files to be attached with email.
  * @param string $from the sender of the email.
  * @param string $to the reciever of the email.
  * @param string $subject the subject of the email.
  * @param string $message the message of the email.			 			  			  					 
  * @throws Exception throws an exception if the file size is greater than a limit or the file extension is not valid or the uploaded file could not be copied
  * 
  * @return boolean $is_sent used to indicate if the email was sent.
  */
 public function SendEmail($attachment_files, $from, $to, $subject, $text)
 {
     try {
         $processed = htmlentities($text);
         if ($processed == $text) {
             $is_html = false;
         } else {
             $is_html = true;
         }
         $message = new \Mail_mime();
         if (!$is_html) {
             $message->setTXTBody($text);
         } else {
             $message->setHTMLBody($text);
         }
         /** If the attachment files were given */
         if (is_array($attachment_files)) {
             for ($count = 0; $count < count($attachment_files); $count++) {
                 $path_of_uploaded_file = $attachment_files[$count];
                 if ($path_of_uploaded_file != "") {
                     $message->addAttachment($path_of_uploaded_file);
                 }
             }
         }
         $body = $message->get();
         $extraheaders = array("From" => $from, "Subject" => $subject, "Reply-To" => $from);
         $headers = $message->headers($extraheaders);
         $mail = new \Mail("mail");
         $is_sent = $mail->send($to, $headers, $body);
         if (!$is_sent) {
             throw new \Exception("Email could not be sent. Details: " . $e->getMessage(), 110);
         } else {
             return true;
         }
     } catch (\Exception $e) {
         throw new \Exception("Email could not be sent. Details: " . $e->getMessage(), 110, $e);
     }
 }
 private function sendEmail($from, $recipients, $subject, $body, $cc, $bcc, $attachments)
 {
     $crlf = "\n";
     $headers = array('From' => $from, 'Return-Path' => $from, 'Subject' => $subject);
     // Creating the Mime message
     $mime = new Mail_mime($crlf);
     $text = false;
     $html = false;
     // Setting the body of the email
     if ($body instanceof string) {
         $text = $body;
         $mime->setTXTBody($text);
     } else {
         if (isset($body['text/html'])) {
             $mime->setHTMLBody($html);
         }
         if (isset($body['text/plain'])) {
             $mime->setTXTBody($text);
         }
     }
     // Add an attachment
     if ($attachments != null) {
         foreach ($attachments as $attachment) {
             $mime->addAttachment($attachment['file'], $attachment['content_type'], $attachment['file_name'], 0);
         }
     }
     // Set body and headers ready for base mail class
     $body = $mime->get();
     $headers = $mime->headers($headers);
     // Sending the email using smtp
     $mail =& Mail::factory("smtp", $smtp_params);
     $result = $mail->send($recipients, $headers, $body);
     if (PEAR::isError($result)) {
         error_log("FIREALARM: Failed to send email to {$to}: " . $result->getMessage());
         return false;
     }
     return $result;
 }
Esempio n. 20
0
 protected function sendFilesets()
 {
     @(require_once 'Mail.php');
     @(require_once 'Mail/mime.php');
     if (!class_exists('Mail_mime')) {
         throw new BuildException('Need the PEAR Mail_mime package to send attachments');
     }
     $mime = new Mail_mime(array('text_charset' => 'UTF-8'));
     $hdrs = array('From' => $this->from, 'Subject' => $this->subject);
     $mime->setTXTBody($this->msg);
     foreach ($this->filesets as $fs) {
         $ds = $fs->getDirectoryScanner($this->project);
         $fromDir = $fs->getDir($this->project);
         $srcFiles = $ds->getIncludedFiles();
         foreach ($srcFiles as $file) {
             $mime->addAttachment($fromDir . DIRECTORY_SEPARATOR . $file, 'application/octet-stream');
         }
     }
     $body = $mime->get();
     $hdrs = $mime->headers($hdrs);
     $mail = Mail::factory($this->backend, $this->backendParams);
     $mail->send($this->tolist, $hdrs, $body);
 }
Esempio n. 21
0
function mail_to($from, $to, $subject, $message, $attachment = "")
{
    include 'pearmail/Mail.php';
    include 'pearmail/Mail/mime.php';
    require_once 'class.html2text.inc';
    $html = $message;
    $h2t =& new html2text($message);
    $text = $h2t->get_text();
    $file = $attachment;
    $crlf = "";
    $hdrs = array('From' => $from, 'To' => $to, 'Subject' => $subject);
    $mime = new Mail_mime();
    $mime->setTXTBody($text);
    $mime->setHTMLBody($html);
    if (!empty($attachment)) {
        $mime->addAttachment($file, 'application/octet-stream');
    }
    $body = $mime->get();
    $hdrs = $mime->headers($hdrs);
    global $smtpinfo;
    $mail =& Mail::factory("smtp", $smtpinfo);
    $mail->send($to, $hdrs, $body);
}
/**
*
*  @utils_mail_mime_send
*
*  @description
*      - send mime email
*
*  @parameters
*      - data
*      -  
*      -  
*
*  @return
*      - result
*              
*/
function utils_mail_mime_send($pdata = null)
{
    //dmp
    $dmp = @var_export($pdata, true);
    debug("utils_mail_mime_send():: DMP [ {$dmp} ]");
    //fmt
    $mfrom = trim($pdata['from']);
    $mto = trim($pdata['to']);
    $msubject = trim($pdata['subject']);
    $text = trim($pdata['text']);
    $html = trim($pdata['html']);
    //attachment
    $attach = $pdata['attach'];
    //misc hdrs
    $crlf = "\n";
    $hdrs = array('From' => $mfrom, 'Subject' => $msubject);
    //mime
    $mime = new Mail_mime($crlf);
    $mime->setTXTBody($text);
    $mime->setHTMLBody($html);
    //attach if can
    for ($i = 0; $i < @count($attach); $i++) {
        //save
        $afile = $attach[$i];
        //chk
        $aret = $mime->addAttachment($afile);
        debug("utils_mail_mime_send():: Attach! [ #{$afile} => {$aret} ]");
    }
    //do not ever try to call these lines in reverse order
    $body = $mime->get();
    $hdrs = $mime->headers($hdrs);
    $mail =& Mail::factory('mail');
    $is_ok = $mail->send($mto, $hdrs, $body);
    debug("utils_mail_mime_send():: Sent! [ #{$is_ok} ]");
    //give it back ;-)
    return $is_ok;
}
Esempio n. 23
0
function sendEMail($par, $file = false)
{
    $recipients = $par['empfaenger'];
    $message_array = $par['message'];
    $from = '*****@*****.**';
    $backend = 'smtp';
    $subject = $message_array['subject'];
    $body_txt = $message_array['body_txt'];
    $crlf = "\n";
    $params = array('host' => '10.149.43.10', 'port' => 25, 'auth' => false, 'username' => false, 'password' => false, 'localhost' => 'localhost', 'timeout' => null, 'debug' => false);
    foreach ($recipients as $recipient) {
        $headers = array('From' => $from, 'To' => $recipient, 'Subject' => $subject);
        $mime = new Mail_mime($crlf);
        $mime->setTXTBody($body_txt);
        if (is_file($file)) {
            $ctype = MIME_Type::autoDetect($file);
            $mime->addAttachment($file, $ctype);
        }
        $body = $mime->get();
        $hdrs = $mime->headers($headers);
        $mail =& Mail::factory($backend, $params);
        $mail->send($recipient, $hdrs, $body);
    }
}
Esempio n. 24
0
function send_email($email, $filename)
{
    global $smtp_server, $smtp_port, $smtp_email, $smtp_password;
    $from = '<' . $smtp_email . '>';
    $to = '<' . $email . '>';
    $subject = 'AirScan';
    $html = "<html><body>Hi, your scan is now ready for you. Please find the PDF attached.</body></html>";
    $text = "Hi, your scan is now ready for you. Please find the PDF attached.";
    $headers = array('MIME-Version' => '1.0', 'From' => $from, 'To' => $to, 'Subject' => $subject);
    $crlf = "\n";
    $mime = new Mail_mime(array('eol' => $crlf));
    $mime->setTXTBody($text);
    $mime->setHTMLBody($html);
    $mime->addAttachment($filename, 'application/pdf');
    $body = $mime->get();
    $headers = $mime->headers($headers);
    $smtp = Mail::factory('smtp', array('host' => 'ssl://' . $smtp_server, 'port' => $smtp_port, 'auth' => true, 'username' => $smtp_email, 'password' => $smtp_password));
    $mail = $smtp->send($to, $headers, $body);
    if (PEAR::isError($mail)) {
        echo '<div>' . $mail->getMessage() . '</div>';
    } else {
        echo '<h2>Scan complete. Check your email for the PDF.</h2>';
    }
}
Esempio n. 25
0
 function email_invoice($email_sender, $email_to, $email_cc, $email_bcc, $email_subject, $email_message)
 {
     log_debug("invoice", "Executing email_invoice([options])");
     // external dependency of Mail_Mime
     if (!@(include_once 'Mail.php')) {
         log_write("error", "invoice", "Unable to find Mail module required for sending email");
         return 0;
     }
     if (!@(include_once 'Mail/mime.php')) {
         log_write("error", "invoice", "Unable to find Mail::Mime module required for sending email");
         return 0;
     }
     // track attachment files to tidy up
     $file_attachments = array();
     /*
     	Prepare Email Mime Data & Headers
     */
     // fetch sender address
     //
     // users have the choice of sending as the company or as their own staff email address & name.
     //
     if ($email_sender == "user") {
         // send as the user
         $email_sender = "\"" . user_information("realname") . "\" <" . user_information("contact_email") . ">";
     } else {
         // send as the system
         $email_sender = "\"" . sql_get_singlevalue("SELECT value FROM config WHERE name='COMPANY_NAME'") . "\" <" . sql_get_singlevalue("SELECT value FROM config WHERE name='COMPANY_CONTACT_EMAIL'") . ">";
     }
     // prepare headers
     $mail_headers = array('From' => $email_sender, 'Subject' => $email_subject, 'Cc' => $email_cc, 'Bcc' => $email_bcc);
     $mail_mime = new Mail_mime("\n");
     $mail_mime->setTXTBody($email_message);
     /*
     	Generate a PDF of the invoice and save to tmp file
     */
     log_debug("invoice", "Generating invoice PDF for emailing");
     // generate PDF
     $this->generate_pdf();
     if (error_check()) {
         return 0;
     }
     // save to a temporary file
     if ($this->type == "ar") {
         $tmp_file_invoice = file_generate_name($GLOBALS["config"]["PATH_TMPDIR"] . "/invoice_" . $this->data["code_invoice"] . "", "pdf");
     } else {
         $tmp_file_invoice = file_generate_name($GLOBALS["config"]["PATH_TMPDIR"] . "/quote_" . $this->data["code_quote"] . "", "pdf");
         //$email_template	= sql_get_singlevalue("SELECT value FROM config WHERE name IN('TEMPLATE_QUOTE_EMAIL') LIMIT 1");
     }
     if (!($fhandle = fopen($tmp_file_invoice, "w"))) {
         log_write("error", "invoice", "A fatal error occured whilst writing invoice PDF to file {$tmp_file_invoice}, unable to send email");
         return 0;
     }
     fwrite($fhandle, $this->obj_pdf->output);
     fclose($fhandle);
     // attach
     $mail_mime->addAttachment($tmp_file_invoice, 'application/pdf');
     $file_attachments[] = $tmp_file_invoice;
     /*
     	Fetch Extra Attachments
     
     	Certain billing processes may add file attachments to the journal that should be sent along with the invoice
     	when an email is generated.
     
     	Here we grab those file attachments and send each one.
     */
     $obj_sql_journal = new sql_query();
     $obj_sql_journal->string = "SELECT id FROM journal WHERE journalname='account_ar' AND customid='" . $this->id . "' AND title LIKE 'SERVICE:%'";
     $obj_sql_journal->execute();
     if ($obj_sql_journal->num_rows()) {
         $obj_sql_journal->fetch_array();
         foreach ($obj_sql_journal->data as $data_journal) {
             // there are journaled attachments to send
             //
             // we don't care about any of the journal data, we just need to pull the file attachment from
             // storage, write to disk and then attach to the email
             //
             // fetch file object
             $file_obj = new file_storage();
             $file_obj->data["type"] = "journal";
             $file_obj->data["customid"] = $data_journal["id"];
             if (!$file_obj->load_data_bytype()) {
                 log_write("error", "inc_invoices", "Unable to load file from journal to attach to invoice email - possible file storage issue?");
                 return 0;
             }
             $file_extension = format_file_extension($file_obj->data["file_name"]);
             $file_name = format_file_noextension($file_obj->data["file_name"]);
             $file_ctype = format_file_contenttype($file_extension);
             // we have to write the file to disk before attaching it
             $tmp_file_attach = file_generate_name($GLOBALS["config"]["PATH_TMPDIR"] . "/" . $file_name, $file_extension);
             if (!$file_obj->filedata_write($tmp_file_attach)) {
                 log_write("error", "inc_invoices", "Unable to write file attachments from journal to tmp space");
                 return 0;
             }
             // add to the invoice
             $mail_mime->addAttachment($tmp_file_attach, $file_ctype);
             $file_attachments[] = $tmp_file_attach;
             // cleanup - tmp file will be removed ;ater
             unset($file_obj);
         }
         // end of for each journal item
     }
     // end if sendable journal items
     unset($obj_sql_journal);
     /*
     	Email the invoice
     */
     log_write("debug", "invoice", "Sending generated email....");
     $mail_body = $mail_mime->get();
     $mail_headers = $mail_mime->headers($mail_headers);
     $mail =& Mail::factory('mail', "-f " . $GLOBALS["config"]["COMPANY_CONTACT_EMAIL"]);
     $status = $mail->send($email_to, $mail_headers, $mail_body);
     if (PEAR::isError($status)) {
         log_write("error", "inc_invoice", "An error occured whilst attempting to send the email: " . $status->getMessage() . "");
     } else {
         log_write("debug", "inc_invoice", "Successfully sent email invoice");
         /*
         	Start SQL Transaction to post email to journal
         */
         $sql_obj = new sql_query();
         $sql_obj->trans_begin();
         /*
         	Mark the invoice as having been sent
         */
         $sql_obj = new sql_query();
         $sql_obj->string = "UPDATE account_" . $this->type . " SET date_sent='" . date("Y-m-d") . "', sentmethod='email' WHERE id='" . $this->id . "'";
         $sql_obj->execute();
         /*
         	Add the email information to the journal, including attaching a copy
         	of the generated PDF
         */
         log_write("debug", "inc_invoice", "Uploading PDF and email details to journal...");
         // create journal entry
         $journal = new journal_process();
         $journal->prepare_set_journalname("account_" . $this->type);
         $journal->prepare_set_customid($this->id);
         $journal->prepare_set_type("file");
         $journal->prepare_set_title("EMAIL: {$email_subject}");
         $data["content"] = NULL;
         $data["content"] .= "To:\t" . $email_to . "\n";
         $data["content"] .= "Cc:\t" . $email_cc . "\n";
         $data["content"] .= "Bcc:\t" . $email_bcc . "\n";
         $data["content"] .= "From:\t" . $email_sender . "\n";
         $data["content"] .= "\n";
         $data["content"] .= $email_message;
         $data["content"] .= "\n";
         $journal->prepare_set_content($data["content"]);
         $journal->action_update();
         // create journal entry
         $journal->action_lock();
         // lock it to prevent any changes to historical record of delivered email
         // upload PDF file as an attachement
         $file_obj = new file_storage();
         $file_obj->data["type"] = "journal";
         $file_obj->data["customid"] = $journal->structure["id"];
         if (!$file_obj->action_update_file($tmp_file_invoice)) {
             log_write("error", "inc_invoice", "Unable to upload emailed PDF to journal entry");
         }
         /*
         	Commit
         */
         if (error_check()) {
             $sql_obj->trans_rollback();
         } else {
             $sql_obj->trans_commit();
         }
     }
     // end if successful send
     // cleanup - remove the temporary files
     log_debug("inc_invoice", "Performing cleanup, removing temporary files used for emails");
     foreach ($file_attachments as $filename) {
         log_debug("inc_invoice", "Removing tmp file {$filename}");
         unlink($filename);
     }
     // return
     if (error_check()) {
         return 0;
     } else {
         return 1;
     }
 }
Esempio n. 26
0
function send_mail($sda_FROM_ADDRESS = null, $sda_FROM_PASSWORD = null, $sda_FROM_NAME = null, $sda_TO_ADDRESS = null, $sda_SUBJECT = null, $sda_MESSAGE = null, $sda_FILE = null)
{
    /* - - - - -  условия аварийного завершения функции (НАЧАЛО)  - - - - - */
    if (!$sda_FROM_ADDRESS) {
        return;
    }
    if (!$sda_FROM_PASSWORD) {
        return;
    }
    if (!$sda_TO_ADDRESS) {
        return;
    }
    /* - - - - -  условия аварийного завершения функции (КОНЕЦ)  - - - - - */
    /* - - - - -  подключение пакетов PEAR (НАЧАЛО)  - - - - - */
    require_once "Mail.php";
    require_once "Mail/mime.php";
    /* - - - - -  подключение пакетов PEAR (КОНЕЦ)  - - - - - */
    /* - - - - -  формирование письма (НАЧАЛО)  - - - - - */
    if ($sda_FROM_NAME) {
        $sda_auxiliary_variable = $sda_FROM_NAME . ' <' . $sda_FROM_ADDRESS . '>';
    } else {
        $sda_auxiliary_variable = $sda_FROM_ADDRESS;
    }
    $sda_HEADER = array('From' => $sda_auxiliary_variable, 'To' => $sda_TO_ADDRESS, 'Subject' => $sda_SUBJECT);
    $sda_MIME = new Mail_mime(array("html_charset" => "UTF-8", "text_charset" => "UTF-8", "head_charset" => "UTF-8"));
    $sda_MIME->setHTMLBody('<html><body>' . $sda_MESSAGE . '</body></html>');
    $sda_MIME->addAttachment($sda_FILE, 'application/octet-stream');
    $sda_BODY = $sda_MIME->get();
    $sda_EXTENDED_HEADER = $sda_MIME->headers($sda_HEADER);
    /* - - - - -  формирование письма (КОНЕЦ)  - - - - - */
    /* - - - - -  данные для получения доступа к исходящему почтовому серверу по протоколу SSL (НАЧАЛО)  - - - - - */
    $sda_SMTP = array();
    $sda_SMTP["host"] = "ssl://smtp.gmail.com";
    // константа
    $sda_SMTP["port"] = "465";
    // константа
    $sda_SMTP["auth"] = true;
    $sda_SMTP["username"] = $sda_FROM_ADDRESS;
    $sda_SMTP["password"] = $sda_FROM_PASSWORD;
    /* - - - - -  данные для получения доступа к исходящему почтовому серверу по протоколу SSL (КОНЕЦ)  - - - - - */
    /* - - - - -  установление соединения и отправка письма (НАЧАЛО)  - - - - - */
    $sda_SMTP =& Mail::factory('smtp', $sda_SMTP);
    $sda_ERROR = $sda_SMTP->send($sda_TO_ADDRESS, $sda_EXTENDED_HEADER, $sda_BODY);
    if (PEAR::isError($sda_ERROR)) {
        echo $sda_ERROR->getMessage();
    }
    /* - - - - -  установление соединения и отправка письма (КОНЕЦ)  - - - - - */
}
Esempio n. 27
0
 function send($to, $subject, $message, $attachments = null, $options = null)
 {
     global $cfg;
     //Get SMTP info IF enabled!
     $smtp = array();
     if ($this->isSMTPEnabled() && ($info = $this->getSMTPInfo())) {
         //is SMTP enabled for the current email?
         $smtp = $info;
     } elseif ($cfg && ($email = $cfg->getDefaultSMTPEmail()) && $email->isSMTPEnabled()) {
         //What about global SMTP setting?
         if ($email->allowSpoofing() && ($info = $email->getSMTPInfo())) {
             //If spoofing is allowed..then continue.
             $smtp = $info;
         } elseif ($email->getId() != $this->getId()) {
             //No spoofing allowed. Send it via the default SMTP email.
             return $email->send($to, $subject, $message, $attachments, $options);
         }
     }
     //Get the goodies
     require_once 'Mail.php';
     // PEAR Mail package
     require_once 'Mail/mime.php';
     // PEAR Mail_Mime packge
     //do some cleanup
     $eol = "\n";
     $to = preg_replace("/(\r\n|\r|\n)/s", '', trim($to));
     $subject = stripslashes(preg_replace("/(\r\n|\r|\n)/s", '', trim($subject)));
     $body = stripslashes(preg_replace("/(\r\n|\r)/s", "\n", trim($message)));
     $fromname = $this->getName();
     $from = sprintf('"%s"<%s>', $fromname ? $fromname : $this->getEmail(), $this->getEmail());
     $headers = array('From' => $from, 'To' => $to, 'Subject' => $subject, 'Date' => date('D,d M Y H:i:s O'), 'Message-ID' => '<' . Misc::randCode(6) . '' . time() . '-' . $this->getEmail() . '>', 'X-Mailer' => 'osTicket v1.7', 'Content-Type' => 'text/html; charset="UTF-8"');
     $mime = new Mail_mime();
     $mime->setTXTBody($body);
     //XXX: Attachments
     if ($attachments) {
         foreach ($attachments as $attachment) {
             if ($attachment['file_id'] && ($file = AttachmentFile::lookup($attachment['file_id']))) {
                 $mime->addAttachment($file->getData(), $file->getType(), $file->getName(), false);
             } elseif ($attachment['file'] && file_exists($attachment['file']) && is_readable($attachment['file'])) {
                 $mime->addAttachment($attachment['file'], $attachment['type'], $attachment['name']);
             }
         }
     }
     $options = array('head_encoding' => 'quoted-printable', 'text_encoding' => 'quoted-printable', 'html_encoding' => 'base64', 'html_charset' => 'utf-8', 'text_charset' => 'utf-8');
     //encode the body
     $body = $mime->get($options);
     //encode the headers.
     $headers = $mime->headers($headers);
     if ($smtp) {
         //Send via SMTP
         $mail = mail::factory('smtp', array('host' => $smtp['host'], 'port' => $smtp['port'], 'auth' => $smtp['auth'] ? true : false, 'username' => $smtp['username'], 'password' => $smtp['password'], 'timeout' => 20, 'debug' => false));
         $result = $mail->send($to, $headers, $body);
         if (!PEAR::isError($result)) {
             return true;
         }
         $alert = sprintf("Unable to email via %s:%d [%s]\n\n%s\n", $smtp['host'], $smtp['port'], $smtp['username'], $result->getMessage());
         Sys::log(LOG_ALERT, 'SMTP Error', $alert, false);
         //print_r($result);
     }
     //No SMTP or it failed....use php's native mail function.
     $mail = mail::factory('mail');
     return PEAR::isError($mail->send($to, $headers, $body)) ? false : true;
 }
Esempio n. 28
0
 /**
  * Mail form
  *
  * @param	integer	$form_id
  * @param	array	$data
  * @return	boolean	true on succes, or false on fail
  */
 function mail($form_id, $data)
 {
     $sm = vivvo_lite_site::get_instance();
     if (!vivvo_hooks_manager::call('form_builder_mail', array(&$form_id, &$delete))) {
         return vivvo_hooks_manager::get_status();
     }
     require_once VIVVO_FS_FRAMEWORK . 'PEAR/Mail.php';
     $form_list = new FormBuilderForms_list();
     $form = $form_list->get_form_by_id($form_id);
     $data = array_map('urldecode', $data);
     $attachments = array();
     if ($form !== false) {
         $form_element_list = new FormBuilderFields_list($this->_site_manager);
         $form_element_list->get_elements_by_form_id($form->id);
         $message = '';
         foreach ($form_element_list->list as $field) {
             if ($field->required && !key_exists($field->name, $data) && $data[$field->name] !== '' && $field->type != 'file_upload') {
                 $this->set_error_code(10712);
                 return false;
             } else {
                 if ($field->required && $field->type == 'file_upload' && empty($_FILES['PFB_' . $field->name]['name'])) {
                     $this->set_error_code(10712);
                     return false;
                 }
             }
             if (key_exists($field->name, $data)) {
                 if ($field->reg_exp) {
                     if (!preg_match('/^' . $field->reg_exp . '$/', $data[$field->name])) {
                         $this->set_error_code(10713);
                         return false;
                     }
                 }
                 if ($field->type != 'submit') {
                     if ($field->label != '') {
                         $message .= $field->label . ': ' . $data[$field->name] . "\n";
                     } else {
                         $message .= $field->name . ': ' . $data[$field->name] . "\n";
                     }
                 }
             }
             if ($field->type == 'file_upload' && isset($_FILES['PFB_' . $field->name])) {
                 $attachments[] = 'PFB_' . $field->name;
             }
         }
         if ($form->email) {
             $files = array();
             if (count($attachments)) {
                 foreach ($attachments as $attachment) {
                     if ($_FILES[$attachment]['error'] == 0 && $_FILES[$attachment]['size'] > 0 && $_FILES[$attachment]['size'] <= 2 * 1024 * 1024 && in_array(substr($_FILES[$attachment]['name'], strrpos($_FILES[$attachment]['name'], '.') + 1), array_map('trim', explode(',', VIVVO_ALLOWED_EXTENSIONS))) && is_uploaded_file($_FILES[$attachment]['tmp_name'])) {
                         $filename = VIVVO_FS_INSTALL_ROOT . 'cache/' . md5(uniqid(mt_rand(), true)) . basename($_FILES[$attachment]['name']);
                         if (move_uploaded_file($_FILES[$attachment]['tmp_name'], $filename)) {
                             $files[] = array($filename, basename($_FILES[$attachment]['name']));
                         }
                     }
                 }
             }
             $headers['From'] = VIVVO_ADMINISTRATORS_EMAIL;
             $headers['Subject'] = "=?UTF-8?B?" . base64_encode($form->title) . "?=";
             if (!count($files)) {
                 $headers['Content-Type'] = "text/plain; charset=UTF-8;";
             } else {
                 require_once VIVVO_FS_INSTALL_ROOT . 'lib/vivvo/framework/PEAR/Mail/mime.php';
                 $mime = new Mail_mime();
                 $mime->setTXTBody($message);
                 foreach ($files as $file) {
                     $mime->addAttachment($file[0], 'application/octet-stream', $file[1]);
                 }
                 $message = $mime->get();
                 $headers = $mime->headers($headers);
                 foreach ($files as $file) {
                     @unlink($file[0]);
                 }
             }
             if (VIVVO_EMAIL_SMTP_PHP == 1) {
                 $mail_object = new Mail();
                 $mail_object->send($form->email, $headers, $message);
             } else {
                 $mail_options['driver'] = 'smtp';
                 $mail_options['host'] = VIVVO_EMAIL_SMTP_HOST;
                 $mail_options['port'] = VIVVO_EMAIL_SMTP_PORT;
                 $mail_options['localhost'] = 'localhost';
                 if (VIVVO_EMAIL_SMTP_PASSWORD != '' && VIVVO_EMAIL_SMTP_USERNAME != '') {
                     $mail_options['auth'] = true;
                     $mail_options['username'] = VIVVO_EMAIL_SMTP_USERNAME;
                     $mail_options['password'] = VIVVO_EMAIL_SMTP_PASSWORD;
                 } else {
                     $mail_options['auth'] = false;
                     $mail_options['username'] = '';
                     $mail_options['password'] = '';
                 }
                 $mail_object = Mail::factory('smtp', $mail_options);
                 $mail_object->send($form->email, $headers, $message);
             }
         }
         if ($form->message) {
             return $form->message;
         } else {
             return ' ';
         }
     }
 }
 /**
  * Compose a message.
  *
  * @param int $job_id
  *   ID of the Job associated with this message.
  * @param int $event_queue_id
  *   ID of the EventQueue.
  * @param string $hash
  *   Hash of the EventQueue.
  * @param string $contactId
  *   ID of the Contact.
  * @param string $email
  *   Destination address.
  * @param string $recipient
  *   To: of the recipient.
  * @param bool $test
  *   Is this mailing a test?.
  * @param $contactDetails
  * @param $attachments
  * @param bool $isForward
  *   Is this mailing compose for forward?.
  * @param string $fromEmail
  *   Email address of who is forwardinf it.
  *
  * @param null $replyToEmail
  *
  * @return Mail_mime               The mail object
  */
 public function compose($job_id, $event_queue_id, $hash, $contactId, $email, &$recipient, $test, $contactDetails, &$attachments, $isForward = FALSE, $fromEmail = NULL, $replyToEmail = NULL)
 {
     $config = CRM_Core_Config::singleton();
     $this->getTokens();
     if ($this->_domain == NULL) {
         $this->_domain = CRM_Core_BAO_Domain::getDomain();
     }
     list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward);
     //set from email who is forwarding it and not original one.
     if ($fromEmail) {
         unset($headers['From']);
         $headers['From'] = "<{$fromEmail}>";
     }
     if ($replyToEmail && $fromEmail != $replyToEmail) {
         $headers['Reply-To'] = "{$replyToEmail}";
     }
     if ($contactDetails) {
         $contact = $contactDetails;
     } elseif ($contactId === 0) {
         //anonymous user
         $contact = array();
         CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
     } else {
         $params = array(array('contact_id', '=', $contactId, 0, 0));
         list($contact) = CRM_Contact_BAO_Query::apiQuery($params);
         //CRM-4524
         $contact = reset($contact);
         if (!$contact || is_a($contact, 'CRM_Core_Error')) {
             CRM_Core_Error::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1', array(1 => $contactId)));
             // setting this because function is called by reference
             //@todo test not calling function by reference
             $res = NULL;
             return $res;
         }
         // also call the hook to get contact details
         CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
     }
     $pTemplates = $this->getPreparedTemplates();
     $pEmails = array();
     foreach ($pTemplates as $type => $pTemplate) {
         $html = $type == 'html' ? TRUE : FALSE;
         $pEmails[$type] = array();
         $pEmail =& $pEmails[$type];
         $template =& $pTemplates[$type]['template'];
         $tokens =& $pTemplates[$type]['tokens'];
         $idx = 0;
         if (!empty($tokens)) {
             foreach ($tokens as $idx => $token) {
                 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
                 array_push($pEmail, $template[$idx]);
                 array_push($pEmail, $token_data);
             }
         } else {
             array_push($pEmail, $template[$idx]);
         }
         if (isset($template[$idx + 1])) {
             array_push($pEmail, $template[$idx + 1]);
         }
     }
     $html = NULL;
     if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
         $html =& $pEmails['html'];
     }
     $text = NULL;
     if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
         $text =& $pEmails['text'];
     }
     // push the tracking url on to the html email if necessary
     if ($this->open_tracking && $html) {
         array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL . "extern/open.php?q={$event_queue_id}\" width='1' height='1' alt='' border='0'>");
     }
     $message = new Mail_mime("\n");
     $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
     if ($useSmarty) {
         $smarty = CRM_Core_Smarty::singleton();
         // also add the contact tokens to the template
         $smarty->assign_by_ref('contact', $contact);
     }
     $mailParams = $headers;
     if ($text && ($test || $contact['preferred_mail_format'] == 'Text' || $contact['preferred_mail_format'] == 'Both' || $contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))) {
         $textBody = implode('', $text);
         if ($useSmarty) {
             $textBody = $smarty->fetch("string:{$textBody}");
         }
         $mailParams['text'] = $textBody;
     }
     if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' || $contact['preferred_mail_format'] == 'Both'))) {
         $htmlBody = implode('', $html);
         if ($useSmarty) {
             $htmlBody = $smarty->fetch("string:{$htmlBody}");
         }
         $mailParams['html'] = $htmlBody;
     }
     if (empty($mailParams['text']) && empty($mailParams['html'])) {
         // CRM-9833
         // something went wrong, lets log it and return null (by reference)
         CRM_Core_Error::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1', array(1 => $email)));
         $res = NULL;
         return $res;
     }
     $mailParams['attachments'] = $attachments;
     $mailingSubject = CRM_Utils_Array::value('subject', $pEmails);
     if (is_array($mailingSubject)) {
         $mailingSubject = implode('', $mailingSubject);
     }
     $mailParams['Subject'] = $mailingSubject;
     $mailParams['toName'] = CRM_Utils_Array::value('display_name', $contact);
     $mailParams['toEmail'] = $email;
     // Add job ID to mailParams for external email delivery service to utilise
     $mailParams['job_id'] = $job_id;
     CRM_Utils_Hook::alterMailParams($mailParams, 'civimail');
     // CRM-10699 support custom email headers
     if (!empty($mailParams['headers'])) {
         $headers = array_merge($headers, $mailParams['headers']);
     }
     //cycle through mailParams and set headers array
     foreach ($mailParams as $paramKey => $paramValue) {
         //exclude values not intended for the header
         if (!in_array($paramKey, array('text', 'html', 'attachments', 'toName', 'toEmail'))) {
             $headers[$paramKey] = $paramValue;
         }
     }
     if (!empty($mailParams['text'])) {
         $message->setTxtBody($mailParams['text']);
     }
     if (!empty($mailParams['html'])) {
         $message->setHTMLBody($mailParams['html']);
     }
     if (!empty($mailParams['attachments'])) {
         foreach ($mailParams['attachments'] as $fileID => $attach) {
             $message->addAttachment($attach['fullPath'], $attach['mime_type'], $attach['cleanName']);
         }
     }
     //pickup both params from mail params.
     $toName = trim($mailParams['toName']);
     $toEmail = trim($mailParams['toEmail']);
     if ($toName == $toEmail || strpos($toName, '@') !== FALSE) {
         $toName = NULL;
     } else {
         $toName = CRM_Utils_Mail::formatRFC2822Name($toName);
     }
     $headers['To'] = "{$toName} <{$toEmail}>";
     $headers['Precedence'] = 'bulk';
     // Will test in the mail processor if the X-VERP is set in the bounced email.
     // (As an option to replace real VERP for those that can't set it up)
     $headers['X-CiviMail-Bounce'] = $verp['bounce'];
     //CRM-5058
     //token replacement of subject
     $headers['Subject'] = $mailingSubject;
     CRM_Utils_Mail::setMimeParams($message);
     $headers = $message->headers($headers);
     //get formatted recipient
     $recipient = $headers['To'];
     // make sure we unset a lot of stuff
     unset($verp);
     unset($urls);
     unset($params);
     unset($contact);
     unset($ids);
     return $message;
 }
Esempio n. 30
0
 function sendpear($from, $subject, $html, $mimetype, $mailaddr, $f2)
 {
     global $setctl, $cfg;
     include 'Mail.php';
     include $cfg['pearmailpath'] . 'mime.php';
     include $cfg['pearmailpath'] . 'mimeDecode.php';
     $result = false;
     $hdrs = array('From' => $from, 'To' => $mailaddr, 'Subject' => $subject, 'Date' => date('r'));
     if (class_exists('Mail_mime')) {
         $mime = new Mail_mime($this->crlf);
         $mime->setHTMLBody($html);
         $mime->addAttachment($f2->fullpath, $mimetype);
         $body = $mime->get();
         $hdrs = $mime->headers($hdrs);
         $params['host'] = $setctl->get('smtphost');
         $params['port'] = $setctl->get('smtpport');
         $params['include_bodies'] = true;
         $params['decode_bodies'] = true;
         $params['decode_headers'] = true;
         $params['auth'] = false;
         $mail =& Mail::factory('smtp', $params);
         $result = $mail->send($mailaddr, $hdrs, $body);
         if (is_object($result)) {
             return false;
         }
     }
     return $result;
 }