/**
  * Miscellaneous calls to improve test coverage and some small tests
  */
 function test_Miscellaneous()
 {
     $this->assertEquals('application/pdf', PHPMailer::_mime_types('pdf'), 'MIME TYPE lookup failed');
     $this->Mail->AddCustomHeader('SomeHeader: Some Value');
     $this->Mail->ClearCustomHeaders();
     $this->Mail->ClearAttachments();
     $this->Mail->IsHTML(false);
     $this->Mail->IsSMTP();
     $this->Mail->IsMail();
     $this->Mail->IsSendMail();
     $this->Mail->IsQmail();
     $this->Mail->SetLanguage('fr');
     $this->Mail->Sender = '';
     $this->Mail->CreateHeader();
     $this->assertFalse($this->Mail->set('x', 'y'), 'Invalid property set succeeded');
     $this->assertTrue($this->Mail->set('Timeout', 11), 'Valid property set failed');
     //Test pathinfo
     $a = '/mnt/files/飛兒樂 團光茫.mp3';
     $q = PHPMailer::mb_pathinfo($a);
     $this->assertEquals($q['dirname'], '/mnt/files', 'UNIX dirname not matched');
     $this->assertEquals($q['basename'], '飛兒樂 團光茫.mp3', 'UNIX basename not matched');
     $this->assertEquals($q['extension'], 'mp3', 'UNIX extension not matched');
     $this->assertEquals($q['filename'], '飛兒樂 團光茫', 'UNIX filename not matched');
     $this->assertEquals(PHPMailer::mb_pathinfo($a, PATHINFO_DIRNAME), '/mnt/files', 'Dirname path element not matched');
     $this->assertEquals(PHPMailer::mb_pathinfo($a, 'filename'), '飛兒樂 團光茫', 'Filename path element not matched');
     $a = 'c:\\mnt\\files\\飛兒樂 團光茫.mp3';
     $q = PHPMailer::mb_pathinfo($a);
     $this->assertEquals($q['dirname'], 'c:\\mnt\\files', 'Windows dirname not matched');
     $this->assertEquals($q['basename'], '飛兒樂 團光茫.mp3', 'Windows basename not matched');
     $this->assertEquals($q['extension'], 'mp3', 'Windows extension not matched');
     $this->assertEquals($q['filename'], '飛兒樂 團光茫', 'Windows filename not matched');
 }
Example #2
0
 /**
  * send an email
  *
  * @param string $toaddress
  * @param string $toname
  * @param string $subject
  * @param string $mailtext
  * @param string $fromaddress
  * @param string $fromname
  * @param bool $html
  */
 public static function send($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname, $html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '')
 {
     $SMTPMODE = OC_Config::getValue('mail_smtpmode', 'sendmail');
     $SMTPHOST = OC_Config::getValue('mail_smtphost', '127.0.0.1');
     $SMTPAUTH = OC_Config::getValue('mail_smtpauth', false);
     $SMTPUSERNAME = OC_Config::getValue('mail_smtpname', '');
     $SMTPPASSWORD = OC_Config::getValue('mail_smtppassword', '');
     $mailo = new PHPMailer(true);
     if ($SMTPMODE == 'sendmail') {
         $mailo->IsSendmail();
     } elseif ($SMTPMODE == 'smtp') {
         $mailo->IsSMTP();
     } elseif ($SMTPMODE == 'qmail') {
         $mailo->IsQmail();
     } else {
         $mailo->IsMail();
     }
     $mailo->Host = $SMTPHOST;
     $mailo->SMTPAuth = $SMTPAUTH;
     $mailo->Username = $SMTPUSERNAME;
     $mailo->Password = $SMTPPASSWORD;
     $mailo->From = $fromaddress;
     $mailo->FromName = $fromname;
     $mailo->Sender = $fromaddress;
     $a = explode(' ', $toaddress);
     try {
         foreach ($a as $ad) {
             $mailo->AddAddress($ad, $toname);
         }
         if ($ccaddress != '') {
             $mailo->AddCC($ccaddress, $ccname);
         }
         if ($bcc != '') {
             $mailo->AddBCC($bcc);
         }
         $mailo->AddReplyTo($fromaddress, $fromname);
         $mailo->WordWrap = 50;
         if ($html == 1) {
             $mailo->IsHTML(true);
         } else {
             $mailo->IsHTML(false);
         }
         $mailo->Subject = $subject;
         if ($altbody == '') {
             $mailo->Body = $mailtext . OC_MAIL::getfooter();
             $mailo->AltBody = '';
         } else {
             $mailo->Body = $mailtext;
             $mailo->AltBody = $altbody;
         }
         $mailo->CharSet = 'UTF-8';
         $mailo->Send();
         unset($mailo);
         OC_Log::write('mail', 'Mail from ' . $fromname . ' (' . $fromaddress . ')' . ' to: ' . $toname . '(' . $toaddress . ')' . ' subject: ' . $subject, OC_Log::DEBUG);
     } catch (Exception $exception) {
         OC_Log::write('mail', $exception->getMessage(), OC_Log::ERROR);
         throw $exception;
     }
 }
 /**
  * Test sending using Qmail.
  */
 public function testQmailSend()
 {
     //Only run if we have qmail installed
     if (file_exists('/var/qmail/bin/qmail-inject')) {
         $this->Mail->Body = 'Sending via qmail';
         $this->BuildBody();
         $subject = $this->Mail->Subject;
         $this->Mail->Subject = $subject . ': qmail';
         $this->Mail->IsQmail();
         $this->assertTrue($this->Mail->Send(), $this->Mail->ErrorInfo);
     } else {
         $this->markTestSkipped('Qmail is not installed');
     }
 }
Example #4
0
 /**
  * Constructor.
  */
 function __construct()
 {
     require_once PHPMAILER_CLASS;
     require_once PHPMAILER_SMTP;
     require_once PHPMAILER_POP3;
     // Inicializa la instancia PHPMailer.
     $mail = new \PHPMailer();
     // Define  el idioma para los mensajes de error.
     $mail->SetLanguage("es", PHPMAILER_LANGS);
     // Define la codificación de caracteres del mensaje.
     $mail->CharSet = "UTF-8";
     // Define el ajuste de texto a un número determinado de caracteres en el cuerpo del mensaje.
     $mail->WordWrap = 50;
     // Define el tipo de gestor de correo
     switch (GOTEO_MAIL_TYPE) {
         default:
         case "mail":
             $mail->isMail();
             // set mailer to use PHP mail() function.
             break;
         case "sendmail":
             $mail->IsSendmail();
             // set mailer to use $Sendmail program.
             break;
         case "qmail":
             $mail->IsQmail();
             // set mailer to use qmail MTA.
             break;
         case "smtp":
             $mail->IsSMTP();
             // set mailer to use SMTP
             $mail->SMTPAuth = GOTEO_MAIL_SMTP_AUTH;
             // enable SMTP authentication
             $mail->SMTPSecure = GOTEO_MAIL_SMTP_SECURE;
             // sets the prefix to the servier
             $mail->Host = GOTEO_MAIL_SMTP_HOST;
             // specify main and backup server
             $mail->Port = GOTEO_MAIL_SMTP_PORT;
             // set the SMTP port
             $mail->Username = GOTEO_MAIL_SMTP_USERNAME;
             // SMTP username
             $mail->Password = GOTEO_MAIL_SMTP_PASSWORD;
             // SMTP password
             break;
     }
     $this->mail = $mail;
 }
Example #5
0
 /**
  * Miscellaneous calls to improve test coverage and some small tests
  */
 function test_Miscellaneous()
 {
     $this->assertEquals('application/pdf', PHPMailer::_mime_types('pdf'), 'MIME TYPE lookup failed');
     $this->Mail->AddCustomHeader('SomeHeader: Some Value');
     $this->Mail->ClearCustomHeaders();
     $this->Mail->ClearAttachments();
     $this->Mail->IsHTML(false);
     $this->Mail->IsSMTP();
     $this->Mail->IsMail();
     $this->Mail->IsSendMail();
     $this->Mail->IsQmail();
     $this->Mail->SetLanguage('fr');
     $this->Mail->Sender = '';
     $this->Mail->CreateHeader();
     $this->assertFalse($this->Mail->set('x', 'y'), 'Invalid property set succeeded');
     $this->assertTrue($this->Mail->set('Timeout', 11), 'Valid property set failed');
 }
Example #6
0
function send_mail($mail_to, $mail_body, $mail_subject = 'No title', $mail_name = 'No name', $mail_from = '', $mail_priority = 3, $mail_wordwrap = 50, $mail_altbody = '')
{
    global $GO_CONFIG;
    //	$mail_to='*****@*****.**';
    //	$mail_from = '*****@*****.**';
    //	$mail_name = "333";
    //	$mail_subject = 'subject';
    //	$mail_body = '123456789';
    //	$mail_altbody = 'qqqqqqqqqqqqqqqq';
    require $GO_CONFIG->class_path . "phpmailer/class.phpmailer.php";
    require $GO_CONFIG->class_path . "phpmailer/class.smtp.php";
    $mail = new PHPMailer();
    $mail->PluginDir = $GO_CONFIG->class_path . 'phpmailer/';
    $mail->SetLanguage($php_mailer_lang, $GO_CONFIG->class_path . 'phpmailer/language/');
    switch ($GO_CONFIG->mailer) {
        case 'smtp':
            $mail->Host = $GO_CONFIG->smtp_server;
            $mail->Port = $GO_CONFIG->smtp_port;
            $mail->IsSMTP();
            break;
        case 'qmail':
            $mail->IsQmail();
            break;
        case 'sendmail':
            $mail->IsSendmail();
            break;
        case 'mail':
            $mail->IsMail();
            break;
    }
    $mail->Priority = $mail_priority;
    $mail->Sender = $mail_from;
    $mail->From = $mail_from;
    $mail->FromName = $mail_name;
    $mail->AddReplyTo($mail_from, $mail_name);
    $mail->WordWrap = $mail_wordwrap;
    //    $mail->Encoding = "quoted-printable";
    $mail->IsHTML(true);
    $mail->Subject = $mail_subject;
    $mail->AddAddress($mail_to);
    $mail->Body = $mail_body;
    $mail->AltBody = $mail_altbody;
    if (!$mail->Send()) {
        return '<p class="Error">' . $ml_send_error . ' ' . $mail->ErrorInfo . '</p>';
    }
}
function dbem_send_mail($subject = "no title", $body = "No message specified", $receiver = '')
{
    global $smtpsettings, $phpmailer, $cformsSettings;
    if (file_exists(dirname(__FILE__) . '/class.phpmailer.php') && !class_exists('PHPMailer')) {
        require_once dirname(__FILE__) . '/class.phpmailer.php';
        require_once dirname(__FILE__) . '/class.smtp.php';
    }
    $mail = new PHPMailer();
    $mail->ClearAllRecipients();
    $mail->ClearAddresses();
    $mail->ClearAttachments();
    $mail->CharSet = 'utf-8';
    $mail->SetLanguage('en', dirname(__FILE__) . '/');
    $mail->PluginDir = dirname(__FILE__) . '/';
    get_option('dbem_rsvp_mail_send_method') == 'qmail' ? $mail->IsQmail() : ($mail->Mailer = get_option('dbem_rsvp_mail_send_method'));
    $mail->Host = get_option('dbem_smtp_host');
    $mail->port = get_option('dbem_rsvp_mail_port');
    if (get_option('dbem_rsvp_mail_SMTPAuth') == '1') {
        $mail->SMTPAuth = TRUE;
    }
    $mail->Username = get_option('dbem_smtp_username');
    $mail->Password = get_option('dbem_smtp_password');
    $mail->From = get_option('dbem_mail_sender_address');
    //$mail->SMTPDebug = true;
    $mail->FromName = get_option('dbem_mail_sender_name');
    // This is the from name in the email, you can put anything you like here
    $mail->Body = $body;
    $mail->Subject = $subject;
    $mail->AddAddress($receiver);
    if (!$mail->Send()) {
        echo "Message was not sent<br/ >";
        echo "Mailer Error: " . $mail->ErrorInfo;
        // print_r($mailer);
    } else {
        // echo "Message has been sent";
    }
}
Example #8
0
function eme_send_mail($subject,$body, $receiveremail, $receivername='', $replytoemail='', $replytoname='') {

   // don't send empty mails
   if (empty($body) || empty($subject)) return;

   $eme_rsvp_mail_send_method = get_option('eme_rsvp_mail_send_method');
   if (get_option('eme_mail_sender_address') == "") {
      $fromMail = $replytoemail;
      $fromName = $replytoname;
   } else {
      $fromMail = get_option('eme_mail_sender_address');
      $fromName = get_option('eme_mail_sender_name'); // This is the from name in the email, you can put anything you like here
   }
   $eme_bcc_address= get_option('eme_mail_bcc_address');

   if ($eme_rsvp_mail_send_method == 'wp_mail') {
      // Set the correct mail headers
      $headers[] = "From: $fromName <$fromMail>";
      if ($replytoemail != "")
         $headers[] = "ReplyTo: $replytoname <$replytoemail>";
      if (!empty($eme_bcc_address))
         $headers[] = "Bcc: $eme_bcc_address";

      // set the correct content type
      if (get_option('eme_rsvp_send_html') == '1')
          add_filter('wp_mail_content_type',create_function('', 'return "text/html"; '));

      // now send it
      wp_mail( $receiveremail, $subject, $body, $headers );  

      // Reset content-type to avoid conflicts -- http://core.trac.wordpress.org/ticket/23578
      if (get_option('eme_rsvp_send_html') == '1')
         remove_filter('wp_mail_content_type', 'set_html_content_type' );

   } else {
      require_once(ABSPATH . WPINC . "/class-phpmailer.php");
      // there's a bug in class-phpmailer from wordpress, so we need to copy class-smtp.php
      // in this dir for smtp to work
      
      if (class_exists('PHPMailer')) {
         $mail = new PHPMailer();
         $mail->ClearAllRecipients();
         $mail->ClearAddresses();
         $mail->ClearAttachments();
         $mail->CharSet = 'utf-8';
         $mail->SetLanguage('en', dirname(__FILE__).'/');

         $mail->PluginDir = dirname(__FILE__).'/';
         if ($eme_rsvp_mail_send_method == 'qmail')
            $mail->IsQmail();
         else
            $mail->Mailer = $eme_rsvp_mail_send_method;

         if ($eme_rsvp_mail_send_method == 'smtp') {
            if (get_option('eme_smtp_host'))
               $mail->Host = get_option('eme_smtp_host');
            else
               $mail->Host = "localhost";

            if (strstr($mail->Host,'ssl://')) {
               $mail->SMTPSecure="ssl";
               $mail->Host = str_replace("ssl://","",$mail->Host);
            }
            if (strstr($mail->Host,'tls://')) {
               $mail->SMTPSecure="tls";
               $mail->Host = str_replace("tls://","",$mail->Host);
            }

            if (get_option('eme_smtp_port'))
               $mail->port = get_option('eme_smtp_port');
            else
               $mail->port = 25;

            if (get_option('eme_rsvp_mail_SMTPAuth') == '1') {
               $mail->SMTPAuth = true;
               $mail->Username = get_option('eme_smtp_username');
               $mail->Password = get_option('eme_smtp_password');
            }
            if (get_option('eme_smtp_debug'))
               $mail->SMTPDebug = 2;
         }
         $mail->From = $fromMail;
         $mail->FromName = $fromName;
         if (get_option('eme_rsvp_send_html') == '1')
            $mail->MsgHTML($body);
         else
            $mail->Body = $body;
         $mail->Subject = $subject;
         if (!empty($replytoemail))
            $mail->AddReplyTo($replytoemail,$replytoname);
         if (!empty($eme_bcc_address))
            $mail->AddBCC($eme_bcc_address);

         if (!empty($receiveremail)) {
            $mail->AddAddress($receiveremail,$receivername);
            if(!$mail->Send()){
               #echo "<br />Message was not sent<br/ >";
               #echo "Mailer Error: " . $mail->ErrorInfo;
               return false;
            } else {
               return true;
            }
         } else {
            return false;
         }
      }
   }
}
Example #9
0
/**
 * Always use this function for all emails to users
 *
 * @param object $userto user object to send email to. must contain firstname,lastname,preferredname,email
 * @param object $userfrom user object to send email from. If null, email will come from mahara
 * @param string $subject email subject
 * @param string $messagetext text version of email
 * @param string $messagehtml html version of email (will send both html and text)
 * @param array  $customheaders email headers
 * @throws EmailException
 * @throws EmailDisabledException
 */
function email_user($userto, $userfrom, $subject, $messagetext, $messagehtml = '', $customheaders = null)
{
    global $IDPJUMPURL;
    static $mnetjumps = array();
    if (!get_config('sendemail')) {
        // You can entirely disable Mahara from sending any e-mail via the
        // 'sendemail' configuration variable
        return true;
    }
    if (empty($userto)) {
        throw new InvalidArgumentException("empty user given to email_user");
    }
    if (isset($userto->id) && empty($userto->ignoredisabled)) {
        $maildisabled = property_exists($userto, 'maildisabled') ? $userto->maildisabled : get_account_preference($userto->id, 'maildisabled') == 1;
        if ($maildisabled) {
            throw new EmailDisabledException("email for this user has been disabled");
        }
    }
    // If the user is a remote xmlrpc user, trawl through the email text for URLs
    // to our wwwroot and modify the url to direct the user's browser to login at
    // their home site before hitting the link on this site
    if (!empty($userto->mnethostwwwroot) && !empty($userto->mnethostapp)) {
        require_once get_config('docroot') . 'auth/xmlrpc/lib.php';
        // Form the request url to hit the idp's jump.php
        if (isset($mnetjumps[$userto->mnethostwwwroot])) {
            $IDPJUMPURL = $mnetjumps[$userto->mnethostwwwroot];
        } else {
            $mnetjumps[$userto->mnethostwwwroot] = $IDPJUMPURL = PluginAuthXmlrpc::get_jump_url_prefix($userto->mnethostwwwroot, $userto->mnethostapp);
        }
        $wwwroot = get_config('wwwroot');
        $messagetext = preg_replace_callback('%(' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))%', 'localurl_to_jumpurl', $messagetext);
        $messagehtml = preg_replace_callback('%href=["\'`](' . $wwwroot . '([\\w_:\\?=#&@/;.~-]*))["\'`]%', 'localurl_to_jumpurl', $messagehtml);
    }
    require_once 'phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer(true);
    $mail->CharSet = 'UTF-8';
    $smtphosts = get_config('smtphosts');
    if ($smtphosts == 'qmail') {
        // use Qmail system
        $mail->IsQmail();
    } else {
        if (empty($smtphosts)) {
            // use PHP mail() = sendmail
            $mail->IsMail();
        } else {
            $mail->IsSMTP();
            // use SMTP directly
            $mail->Host = get_config('smtphosts');
            if (get_config('smtpuser')) {
                // Use SMTP authentication
                $mail->SMTPAuth = true;
                $mail->Username = get_config('smtpuser');
                $mail->Password = get_config('smtppass');
                $mail->SMTPSecure = get_config('smtpsecure');
                $mail->Port = get_config('smtpport');
                if (get_config('smtpsecure') && !get_config('smtpport')) {
                    // Encrypted connection with no port. Use default one.
                    if (get_config('smtpsecure') == 'ssl') {
                        $mail->Port = 465;
                    } elseif (get_config('smtpsecure') == 'tls') {
                        $mail->Port = 587;
                    }
                }
            }
        }
    }
    if (get_config('bounces_handle') && !empty($userto->id) && empty($maildisabled)) {
        $mail->Sender = generate_email_processing_address($userto->id, $userto);
    }
    if (empty($userfrom) || $userfrom->email == get_config('noreplyaddress')) {
        if (empty($mail->Sender)) {
            $mail->Sender = get_config('noreplyaddress');
        }
        $mail->From = get_config('noreplyaddress');
        $mail->FromName = isset($userfrom->id) ? display_name($userfrom, $userto) : get_config('sitename');
        $customheaders[] = 'Precedence: Bulk';
        // Try to avoid pesky out of office responses
        $messagetext .= "\n\n" . get_string('pleasedonotreplytothismessage') . "\n";
        if ($messagehtml) {
            $messagehtml .= "\n\n<p>" . get_string('pleasedonotreplytothismessage') . "</p>\n";
        }
    } else {
        if (empty($mail->Sender)) {
            $mail->Sender = $userfrom->email;
        }
        $mail->From = $userfrom->email;
        $mail->FromName = display_name($userfrom, $userto);
    }
    $replytoset = false;
    if (!empty($customheaders) && is_array($customheaders)) {
        foreach ($customheaders as $customheader) {
            // To prevent duplicated declaration of the field "Message-ID",
            // don't add it into the $mail->CustomHeader[].
            if (false === stripos($customheader, 'message-id')) {
                // Hack the fields "In-Reply-To" and "References":
                // add touser<userID>
                if (0 === stripos($customheader, 'in-reply-to') || 0 === stripos($customheader, 'references')) {
                    $customheader = preg_replace('/<forumpost(\\d+)/', '<forumpost${1}touser' . $userto->id, $customheader);
                }
                $mail->AddCustomHeader($customheader);
            } else {
                list($h, $msgid) = explode(':', $customheader, 2);
                // Hack the "Message-ID": add touser<userID> to make sure
                // the "Message-ID" is unique
                $msgid = preg_replace('/<forumpost(\\d+)/', '<forumpost${1}touser' . $userto->id, $msgid);
                $mail->MessageID = trim($msgid);
            }
            if (0 === stripos($customheader, 'reply-to')) {
                $replytoset = true;
            }
        }
    }
    $mail->Subject = substr(stripslashes($subject), 0, 900);
    try {
        if ($to = get_config('sendallemailto')) {
            // Admins can configure the system to send all email to a given address
            // instead of whoever would receive it, useful for debugging.
            $usertoname = display_name($userto, $userto, true) . ' (' . get_string('divertingemailto', 'mahara', $to) . ')';
            $mail->addAddress($to);
            $notice = get_string('debugemail', 'mahara', display_name($userto, $userto), $userto->email);
            $messagetext = $notice . "\n\n" . $messagetext;
            if ($messagehtml) {
                $messagehtml = '<p>' . hsc($notice) . '</p>' . $messagehtml;
            }
        } else {
            $usertoname = display_name($userto, $userto);
            $mail->AddAddress($userto->email, $usertoname);
            $to = $userto->email;
        }
        if (!$replytoset) {
            $mail->AddReplyTo($mail->From, $mail->FromName);
        }
    } catch (phpmailerException $e) {
        // If there's a phpmailer error already, assume it's an invalid address
        throw new InvalidEmailException("Cannot send email to {$usertoname} with subject {$subject}. Error from phpmailer was: " . $mail->ErrorInfo);
    }
    $mail->WordWrap = 79;
    if ($messagehtml) {
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = $messagetext;
    } else {
        $mail->IsHTML(false);
        $mail->Body = $messagetext;
    }
    try {
        $sent = $mail->Send();
    } catch (phpmailerException $e) {
        $sent = false;
    }
    if ($sent) {
        if ($logfile = get_config('emaillog')) {
            $docroot = get_config('docroot');
            @($client = (string) $_SERVER['REMOTE_ADDR']);
            @($script = (string) $_SERVER['SCRIPT_FILENAME']);
            if (strpos($script, $docroot) === 0) {
                $script = substr($script, strlen($docroot));
            }
            $line = "{$to} <- {$mail->From} - " . str_shorten_text($mail->Subject, 200);
            @error_log('[' . date("Y-m-d h:i:s") . "] [{$client}] [{$script}] {$line}\n", 3, $logfile);
        }
        if (get_config('bounces_handle')) {
            // Update the count of sent mail
            update_send_count($userto);
        }
        return true;
    }
    throw new EmailException("Couldn't send email to {$usertoname} with subject {$subject}. " . "Error from phpmailer was: " . $mail->ErrorInfo);
}
Example #10
0
function test_mail_direct($tab_new_values, $session, $DEBUG = FALSE)
{
    $session = session_id();
    $PHP_SELF = $_SERVER['PHP_SELF'];
    $destination = $tab_new_values['mail_to'];
    $destination_2 = $tab_new_values['mail_to_2'];
    /*******************************************************************/
    error_reporting(E_ALL);
    echo "<b>Direct Mail Test </b><br><br>\n";
    echo "<b>MAIL:</b><br>From = from@example.com<br>To = {$destination}, {$destination_2}<br><br>\n";
    // preparation du test de mail
    require LIBRARY_PATH . 'phpmailer/class.phpmailer.php';
    $mail = new PHPMailer();
    $mail->SetLanguage("fr", LIBRARY_PATH . "phpmailer/language/");
    $mail->From = "*****@*****.**";
    $mail->FromName = "PHP_CONGES";
    $mail->AddAddress($destination);
    if ($destination_2 != "") {
        $mail->AddAddress($destination_2);
    }
    //$mail->AddAddress("*****@*****.**");                  // name is optional
    //$mail->AddReplyTo("*****@*****.**", "Information");
    $mail->WordWrap = 50;
    // set word wrap to 50 characters
    //$mail->AddAttachment("/var/tmp/file.tar.gz");         // add attachments
    //$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name
    //$mail->IsHTML(true);                                  // set email format to HTML
    $mail->Subject = "test phpmailer / php_conges";
    //$mail->Body    = "This is the HTML message body <b>in bold!</b>";
    //$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
    $mail->Body = "This is the body in plain text for non-HTML mail clients";
    // test envoie du mail
    echo "<b>Mail Test :</b><br>\n";
    echo "<b>send message using PHP mail() function :</b><br>\n";
    $mail->IsMail();
    // send message using PHP mail() function
    if (!$mail->Send()) {
        echo "Message could not be sent. <p>";
        echo "Mailer Error: " . $mail->ErrorInfo . "<br><br>";
    } else {
        echo "Message has been sent.<br><br>\n";
    }
    echo "<b>send message using the Sendmail program :</b><br>\n";
    if (!file_exists("/usr/sbin/sendmail")) {
        echo "/usr/sbin/sendmail doesn't exist.<br><br>\n";
    } else {
        $mail->IsSendmail();
        // send message using the $Sendmail program
        if (!$mail->Send()) {
            echo "Message could not be sent. <p>";
            echo "Mailer Error: " . $mail->ErrorInfo . "<br><br>";
        } else {
            echo "Message has been sent.<br><br>\n";
        }
    }
    echo "<b>send message using the qmail MTA :</b><br>\n";
    if (!file_exists("/var/qmail/bin/sendmail")) {
        echo "/var/qmail/bin/sendmail doesn't exist.<br><br>\n";
    } else {
        $mail->IsQmail();
        // send message using the qmail MTA
        if (!$mail->Send()) {
            echo "Message could not be sent. <p>";
            echo "Mailer Error: " . $mail->ErrorInfo . "<br><br>";
        } else {
            echo "Message has been sent.<br><br>\n";
        }
    }
    echo "<br><br><a href=\"{$PHP_SELF}?session={$session}\" method=\"POST\">" . _('form_retour') . "</a><br>\n";
}
Example #11
0
 public function getPhpMailer()
 {
     require_once 'protected/components/phpMailer/class.phpmailer.php';
     $phpMail = new PHPMailer(true);
     // the true param means it will throw exceptions on errors, which we need to catch
     $phpMail->CharSet = 'utf-8';
     switch (Yii::app()->params->admin->emailType) {
         case 'sendmail':
             $phpMail->IsSendmail();
             break;
         case 'qmail':
             $phpMail->IsQmail();
             break;
         case 'smtp':
             $phpMail->IsSMTP();
             $phpMail->Host = Yii::app()->params->admin->emailHost;
             $phpMail->Port = Yii::app()->params->admin->emailPort;
             $phpMail->SMTPSecure = Yii::app()->params->admin->emailSecurity;
             if (Yii::app()->params->admin->emailUseAuth == 'admin') {
                 $phpMail->SMTPAuth = true;
                 $phpMail->Username = Yii::app()->params->admin->emailUser;
                 $phpMail->Password = Yii::app()->params->admin->emailPass;
             }
             break;
         case 'mail':
         default:
             $phpMail->IsMail();
     }
     return $phpMail;
 }
Example #12
0
// value adjustments
$smtp['auth'] = $smtp['auth'] == "true" ? true : false;
$smtp['password'] = $smtp['password'] != '' ? $smtp['password'] : null;
$smtp['secure'] = $smtp['secure'] != "none" ? $smtp['secure'] : null;
$smtp['username'] = $smtp['username'] != '' ? $smtp['username'] : null;
//send the email
include "resources/phpmailer/class.phpmailer.php";
include "resources/phpmailer/class.smtp.php";
$mail = new PHPMailer();
if (isset($_SESSION['email']['method'])) {
    switch ($_SESSION['email']['method']['text']) {
        case 'sendmail':
            $mail->IsSendmail();
            break;
        case 'qmail':
            $mail->IsQmail();
            break;
        case 'mail':
            $mail->IsMail();
            break;
        default:
            $mail->IsSMTP();
            break;
    }
} else {
    $mail->IsSMTP();
}
$mail->SMTPAuth = $smtp['auth'];
$mail->Host = $smtp['host'];
if ($smtp['port'] != 0) {
    $mail->Port = $smtp['port'];
Example #13
0
function constuct_and_send_mail($objet, $mail_sender_name, $mail_sender_addr, $mail_dest_name, $mail_dest_addr, $num_periode, $DEBUG = FALSE)
{
    /*********************************************/
    // init du mail
    $mail = new PHPMailer();
    if ($_SESSION['config']['serveur_smtp'] == '') {
        if (file_exists('/usr/sbin/sendmail')) {
            $mail->IsSendmail();
        } elseif (file_exists('/var/qmail/bin/sendmail')) {
            $mail->IsQmail();
        } else {
            $mail->IsMail();
        }
        // send message using PHP mail() function
    } else {
        $mail->IsSMTP();
        $mail->Host = $_SESSION['config']['serveur_smtp'];
    }
    // initialisation du langage utilisé par php_mailer
    $mail->SetLanguage('fr', LIBRARY_PATH . 'phpmailer/language/');
    $mail->FromName = $mail_sender_name;
    $mail->From = $mail_sender_addr;
    $mail->AddAddress($mail_dest_addr);
    /*********************************************/
    // recup des infos de l'absence
    $select_abs = 'SELECT conges_periode.p_date_deb,
                    conges_periode.p_demi_jour_deb,
                    conges_periode.p_date_fin,
                    conges_periode.p_demi_jour_fin,
                    conges_periode.p_nb_jours,
                    conges_periode.p_commentaire,
                    conges_type_absence.ta_libelle
                FROM   conges_periode, conges_type_absence
                WHERE  conges_periode.p_num=' . $num_periode . '
                        AND    conges_periode.p_type = conges_type_absence.ta_id;';
    $res_abs = SQL::query($select_abs);
    $rec_abs = $res_abs->fetch_array();
    $tab_date_deb = explode('-', $rec_abs['p_date_deb']);
    // affiche : "23 / 01 / 2008 (am)"
    $sql_date_deb = $tab_date_deb[2] . " / " . $tab_date_deb[1] . " / " . $tab_date_deb[0] . " (" . $rec_abs["p_demi_jour_deb"] . ")";
    $tab_date_fin = explode("-", $rec_abs["p_date_fin"]);
    // affiche : "23 / 01 / 2008 (am)"
    $sql_date_fin = $tab_date_fin[2] . " / " . $tab_date_fin[1] . " / " . $tab_date_fin[0] . " (" . $rec_abs["p_demi_jour_fin"] . ")";
    $sql_nb_jours = $rec_abs["p_nb_jours"];
    $sql_commentaire = $rec_abs["p_commentaire"];
    $sql_type_absence = $rec_abs["ta_libelle"];
    /*********************************************/
    // construction des sujets et corps des messages
    if ($objet == "valid_conges") {
        $key1 = "mail_prem_valid_conges_sujet";
        $key2 = "mail_prem_valid_conges_contenu";
    } elseif ($objet == "accept_conges") {
        $key1 = "mail_valid_conges_sujet";
        $key2 = "mail_valid_conges_contenu";
    } elseif ($objet == "new_demande_resp_absent") {
        $key1 = "mail_new_demande_resp_absent_sujet";
        $key2 = "mail_new_demande_resp_absent_contenu";
    } else {
        $key1 = "mail_" . $objet . "_sujet";
        $key2 = "mail_" . $objet . "_contenu";
    }
    $sujet = $_SESSION['config'][$key1];
    $contenu = $_SESSION['config'][$key2];
    $contenu = str_replace("__URL_ACCUEIL_CONGES__", $_SESSION['config']['URL_ACCUEIL_CONGES'], $contenu);
    $contenu = str_replace("__SENDER_NAME__", $mail_sender_name, $contenu);
    $contenu = str_replace("__DESTINATION_NAME__", $mail_dest_name, $contenu);
    $contenu = str_replace("__NB_OF_DAY__", $sql_nb_jours, $contenu);
    $contenu = str_replace("__DATE_DEBUT__", $sql_date_deb, $contenu);
    $contenu = str_replace("__DATE_FIN__", $sql_date_fin, $contenu);
    $contenu = str_replace("__RETOUR_LIGNE__", "\r\n", $contenu);
    $contenu = str_replace("__COMMENT__", $sql_commentaire, $contenu);
    $contenu = str_replace("__TYPE_ABSENCE__", $sql_type_absence, $contenu);
    // construction du corps du mail
    $mail->Subject = stripslashes(utf8_decode($sujet));
    $mail->Body = stripslashes(utf8_decode($contenu));
    /*********************************************/
    // ENVOI du mail
    if ($DEBUG) {
        echo "SUBJECT = " . $sujet . "<br>\n";
        echo "CONTENU = " . $mail->FromName . " " . $contenu . "<br>\n";
    } else {
        if (count($mail->to) == 0) {
            echo "<b>ERROR : No recipient address for the message!</b><br>\n";
            echo "<b>Message was not sent </b><br>";
        } else {
            if (!$mail->Send()) {
                echo "<b>Message was not sent </b><br>";
                echo "<b>Mailer Error: " . $mail->ErrorInfo . "</b><br>";
            }
        }
    }
}
/**
 * This function mails a text $body to the recipient $to.
 * You can use more than one recipient when using a semikolon separated string with recipients.
 * If you send several emails at once please supply an email object so that it can be re-used over and over. Especially with SMTP connections this speeds up things by 200%.
 * If you supply an email object Do not forget to close the mail connection by calling $mail->SMTPClose();
 *
 * @param mixed $mail This is an PHPMailer object. If null, one will be created automatically and unset afterwards. If supplied it won't be unset.
 * @param string $body Body text of the email in plain text or HTML
 * @param mixed $subject Email subject
 * @param mixed $to
 * @param mixed $from
 * @param mixed $sitename
 * @param mixed $ishtml
 * @param mixed $bouncemail
 * @param mixed $attachment
 * @return bool If successful returns true
 */
function SendEmailMessage($mail, $body, $subject, $to, $from, $sitename, $ishtml = false, $bouncemail = null, $attachment = null, $customheaders = "")
{
    global $emailmethod, $emailsmtphost, $emailsmtpuser, $emailsmtppassword, $defaultlang, $emailsmtpdebug;
    global $rootdir, $maildebug, $maildebugbody, $emailsmtpssl, $clang, $demoModeOnly, $emailcharset;
    if (!is_array($customheaders) && $customheaders == '') {
        $customheaders = array();
    }
    if ($demoModeOnly == true) {
        $maildebug = $clang->gT('Email was not sent because demo-mode is activated.');
        $maildebugbody = '';
        return false;
    }
    if (is_null($bouncemail)) {
        $sender = $from;
    } else {
        $sender = $bouncemail;
    }
    $bUnsetEmail = false;
    if (is_null($mail)) {
        $bUnsetEmail = true;
        $mail = new PHPMailer();
    } else {
        $mail->SMTPKeepAlive = true;
    }
    if (!$mail->SetLanguage($defaultlang, $rootdir . '/classes/phpmailer/language/')) {
        $mail->SetLanguage('en', $rootdir . '/classes/phpmailer/language/');
    }
    $mail->CharSet = $emailcharset;
    if (isset($emailsmtpssl) && trim($emailsmtpssl) !== '' && $emailsmtpssl !== 0) {
        if ($emailsmtpssl === 1) {
            $mail->SMTPSecure = "ssl";
        } else {
            $mail->SMTPSecure = $emailsmtpssl;
        }
    }
    $fromname = '';
    $fromemail = $from;
    if (strpos($from, '<')) {
        $fromemail = substr($from, strpos($from, '<') + 1, strpos($from, '>') - 1 - strpos($from, '<'));
        $fromname = trim(substr($from, 0, strpos($from, '<') - 1));
    }
    $sendername = '';
    $senderemail = $sender;
    if (strpos($sender, '<')) {
        $senderemail = substr($sender, strpos($sender, '<') + 1, strpos($sender, '>') - 1 - strpos($sender, '<'));
        $sendername = trim(substr($sender, 0, strpos($sender, '<') - 1));
    }
    switch ($emailmethod) {
        case "qmail":
            $mail->IsQmail();
            break;
        case "smtp":
            $mail->IsSMTP();
            if ($emailsmtpdebug > 0) {
                $mail->SMTPDebug = true;
            }
            if (strpos($emailsmtphost, ':') > 0) {
                $mail->Host = substr($emailsmtphost, 0, strpos($emailsmtphost, ':'));
                $mail->Port = substr($emailsmtphost, strpos($emailsmtphost, ':') + 1);
            } else {
                $mail->Host = $emailsmtphost;
            }
            $mail->Username = $emailsmtpuser;
            $mail->Password = $emailsmtppassword;
            if (trim($emailsmtpuser) != "") {
                $mail->SMTPAuth = true;
            }
            break;
        case "sendmail":
            $mail->IsSendmail();
            break;
        default:
            //Set to the default value to rule out incorrect settings.
            $emailmethod = "mail";
            $mail->IsMail();
    }
    $mail->SetFrom($fromemail, $fromname);
    $mail->Sender = $senderemail;
    // Sets Return-Path for error notifications
    $toemails = explode(";", $to);
    foreach ($toemails as $singletoemail) {
        if (strpos($singletoemail, '<')) {
            $toemail = substr($singletoemail, strpos($singletoemail, '<') + 1, strpos($singletoemail, '>') - 1 - strpos($singletoemail, '<'));
            $toname = trim(substr($singletoemail, 0, strpos($singletoemail, '<') - 1));
            $mail->AddAddress($toemail, $toname);
        } else {
            $mail->AddAddress($singletoemail);
        }
    }
    if (is_array($customheaders)) {
        foreach ($customheaders as $key => $val) {
            $mail->AddCustomHeader($val);
        }
    }
    $mail->AddCustomHeader("X-Surveymailer: {$sitename} Emailer (LimeSurvey.sourceforge.net)");
    if (get_magic_quotes_gpc() != "0") {
        $body = stripcslashes($body);
    }
    if ($ishtml) {
        $mail->IsHTML(true);
        $mail->Body = $body;
        $mail->AltBody = trim(strip_tags(html_entity_decode($body, ENT_QUOTES, 'UTF-8')));
    } else {
        $mail->IsHTML(false);
        $mail->Body = $body;
    }
    // add the attachment if there is one
    if (!is_null($attachment)) {
        $mail->AddAttachment($attachment);
    }
    if (trim($subject) != '') {
        $mail->Subject = "=?{$emailcharset}?B?" . base64_encode($subject) . "?=";
    }
    if ($emailsmtpdebug > 0) {
        ob_start();
    }
    $sent = $mail->Send();
    $maildebug = $mail->ErrorInfo;
    if ($emailsmtpdebug > 0) {
        $maildebug .= '<li>' . $clang->gT('SMTP debug output:') . '</li><pre>' . strip_tags(ob_get_contents()) . '</pre>';
        ob_end_clean();
    }
    $maildebugbody = $mail->Body;
    $mail->ClearAddresses();
    $mail->ClearCustomHeaders();
    if ($bUnsetEmail) {
        unset($mail);
    }
    return $sent;
}
function jsend_mail($to_name, $to_address, $email_subject, $email_text, $from_email_name, $from_email_address, $block = array(), $attachments_list = '')
{
    global $db, $messageStack, $zco_notifier;
    foreach (array($from_email_address, $to_address, $from_email_name, $to_name, $email_subject) as $key => $value) {
        if (preg_match("/\r/i", $value) || preg_match("/\n/i", $value)) {
            return false;
        }
    }
    // if no text or html-msg supplied, exit
    if (trim($email_text) == '') {
        return false;
    }
    // Parse "from" addresses for "name" <*****@*****.**> structure, and supply name/address info from it.
    if (preg_match("/ *([^<]*) *<([^>]*)> */i", $from_email_address, $regs)) {
        $from_email_name = trim($regs[1]);
        $from_email_address = $regs[2];
    }
    // if email name is same as email address, use the Store Name as the senders 'Name'
    if ($from_email_name == $from_email_address) {
        $from_email_name = STORE_NAME;
    }
    // loop thru multiple email recipients if more than one listed --- (esp for the admin's "Extra" emails)...
    foreach (explode(',', $to_address) as $key => $value) {
        if (preg_match("/ *([^<]*) *<([^>]*)> */i", $value, $regs)) {
            $to_name = str_replace('"', '', trim($regs[1]));
            $to_email_address = $regs[2];
        } elseif (preg_match("/ *([^ ]*) */i", $value, $regs)) {
            $to_email_address = trim($regs[1]);
        }
        if (!isset($to_email_address)) {
            $to_email_address = trim($to_address);
        }
        // if not more than one, just use the main one.
        // ensure the address is valid, to prevent unnecessary delivery failures
        if (!zen_validate_email($to_email_address)) {
            @error_log(sprintf(EMAIL_SEND_FAILED . ' (failed validation)', $to_name, $to_email_address, $email_subject));
            continue;
        }
        // define some additional html message blocks available to templates, then build the html portion.
        if (!isset($block['EMAIL_TO_NAME']) || $block['EMAIL_TO_NAME'] == '') {
            $block['EMAIL_TO_NAME'] = $to_name;
        }
        if (!isset($block['EMAIL_TO_ADDRESS']) || $block['EMAIL_TO_ADDRESS'] == '') {
            $block['EMAIL_TO_ADDRESS'] = $to_email_address;
        }
        if (!isset($block['EMAIL_SUBJECT']) || $block['EMAIL_SUBJECT'] == '') {
            $block['EMAIL_SUBJECT'] = $email_subject;
        }
        if (!isset($block['EMAIL_FROM_NAME']) || $block['EMAIL_FROM_NAME'] == '') {
            $block['EMAIL_FROM_NAME'] = $from_email_name;
        }
        if (!isset($block['EMAIL_FROM_ADDRESS']) || $block['EMAIL_FROM_ADDRESS'] == '') {
            $block['EMAIL_FROM_ADDRESS'] = $from_email_address;
        }
        if (!is_array($block) && $block == '' || $block == 'none') {
            $email_html = '';
        }
        $email_text = strip_tags($email_text);
        // bof: body of the email clean-up
        // clean up &amp; and && from email text
        while (strstr($email_text, '&amp;&amp;')) {
            $email_text = str_replace('&amp;&amp;', '&amp;', $email_text);
        }
        while (strstr($email_text, '&amp;')) {
            $email_text = str_replace('&amp;', '&', $email_text);
        }
        while (strstr($email_text, '&&')) {
            $email_text = str_replace('&&', '&', $email_text);
        }
        // clean up currencies for text emails
        $zen_fix_currencies = preg_split("/[:,]/", CURRENCIES_TRANSLATIONS);
        $size = sizeof($zen_fix_currencies);
        for ($i = 0, $n = $size; $i < $n; $i += 2) {
            $zen_fix_current = $zen_fix_currencies[$i];
            $zen_fix_replace = $zen_fix_currencies[$i + 1];
            if (strlen($zen_fix_current) > 0) {
                while (strpos($email_text, $zen_fix_current)) {
                    $email_text = str_replace($zen_fix_current, $zen_fix_replace, $email_text);
                }
            }
        }
        // fix double quotes
        while (strstr($email_text, '&quot;')) {
            $email_text = str_replace('&quot;', '"', $email_text);
        }
        // prevent null characters
        while (strstr($email_text, chr(0))) {
            $email_text = str_replace(chr(0), ' ', $email_text);
        }
        // fix slashes
        $text = stripslashes($email_text);
        $email_html = stripslashes($email_html);
        $mail = new PHPMailer();
        $lang_code = strtolower($_SESSION['languages_code'] == '' ? 'en' : $_SESSION['languages_code']);
        $mail->SetLanguage($lang_code, DIR_FS_CATALOG . DIR_WS_CLASSES . 'support/');
        $mail->CharSet = defined('CHARSET') ? CHARSET : "iso-8859-1";
        $mail->Encoding = defined('EMAIL_ENCODING_METHOD') ? EMAIL_ENCODING_METHOD : "7bit";
        if ((int) EMAIL_SYSTEM_DEBUG > 0) {
            $mail->SMTPDebug = (int) EMAIL_SYSTEM_DEBUG;
        }
        $mail->WordWrap = 76;
        // set word wrap to 76 characters
        // set proper line-endings based on switch ... important for windows vs linux hosts:
        $mail->LE = EMAIL_LINEFEED == 'CRLF' ? "\r\n" : "\n";
        switch (EMAIL_TRANSPORT) {
            case 'smtp':
                $mail->IsSMTP();
                $mail->Host = trim($block['smtp_addr']);
                if ($block['smtp_port'] != '25' && $block['smtp_port'] != '') {
                    $mail->Port = trim($block['smtp_port']);
                }
                $mail->LE = "\r\n";
                break;
            case 'smtpauth':
                $mail->IsSMTP();
                $mail->SMTPAuth = true;
                $mail->Username = zen_not_null($block['smtp_user']) ? trim($block['smtp_user']) : EMAIL_FROM;
                $mail->Password = trim($block['smtp_pwd']);
                $mail->Host = trim($block['smtp_addr']);
                if ($block['smtp_port'] != '25' && $block['smtp_port'] != '') {
                    $mail->Port = trim($block['smtp_port']);
                }
                $mail->LE = "\r\n";
                // set encryption protocol to allow support for Gmail or other secured email protocols
                if ($block['smtp_port'] == '465' || $block['smtp_port'] == '587' || $block['smtp_addr'] == 'smtp.gmail.com') {
                    $mail->Protocol = 'ssl';
                }
                if (defined('SMTPAUTH_EMAIL_PROTOCOL') && SMTPAUTH_EMAIL_PROTOCOL != 'none') {
                    $mail->Protocol = SMTPAUTH_EMAIL_PROTOCOL;
                    if (SMTPAUTH_EMAIL_PROTOCOL == 'starttls' && defined('SMTPAUTH_EMAIL_CERTIFICATE_CONTEXT')) {
                        $mail->Starttls = true;
                        $mail->Context = SMTPAUTH_EMAIL_CERTIFICATE_CONTEXT;
                    }
                }
                break;
            case 'PHP':
                $mail->IsMail();
                break;
            case 'Qmail':
                $mail->IsQmail();
                break;
            case 'sendmail':
            case 'sendmail-f':
                $mail->LE = "\n";
            default:
                $mail->IsSendmail();
                if (defined('EMAIL_SENDMAIL_PATH')) {
                    $mail->Sendmail = trim(EMAIL_SENDMAIL_PATH);
                }
                break;
        }
        $mail->Subject = $email_subject;
        $mail->From = $from_email_address;
        $mail->FromName = $from_email_name;
        $mail->AddAddress($to_email_address, $to_name);
        // $mail->AddAddress($to_email_address); // (alternate format if no name, since name is optional)
        // $mail->AddBCC(STORE_OWNER_EMAIL_ADDRESS, STORE_NAME);
        // set the reply-to address. If none set yet, then use Store's default email name/address.
        // If sending from contact-us or tell-a-friend page, use the supplied info
        $email_reply_to_address = isset($email_reply_to_address) && $email_reply_to_address != '' ? $email_reply_to_address : (in_array($module, array('contact_us', 'tell_a_friend')) ? $from_email_address : EMAIL_FROM);
        $email_reply_to_name = isset($email_reply_to_name) && $email_reply_to_name != '' ? $email_reply_to_name : (in_array($module, array('contact_us', 'tell_a_friend')) ? $from_email_name : STORE_NAME);
        $mail->AddReplyTo($email_reply_to_address, $email_reply_to_name);
        // if mailserver requires that all outgoing mail must go "from" an email address matching domain on server, set it to store address
        if (EMAIL_SEND_MUST_BE_STORE == 'Yes') {
            $mail->From = EMAIL_FROM;
        }
        if (EMAIL_TRANSPORT == 'sendmail-f' || EMAIL_SEND_MUST_BE_STORE == 'Yes') {
            $mail->Sender = EMAIL_FROM;
        }
        if (EMAIL_USE_HTML == 'true') {
            $email_html = processEmbeddedImages($email_html, $mail);
        }
        // PROCESS FILE ATTACHMENTS
        if ($attachments_list == '') {
            $attachments_list = array();
        }
        if (is_string($attachments_list)) {
            if (file_exists($attachments_list)) {
                $attachments_list = array(array('file' => $attachments_list));
            } elseif (file_exists(DIR_FS_CATALOG . $attachments_list)) {
                $attachments_list = array(array('file' => DIR_FS_CATALOG . $attachments_list));
            } else {
                $attachments_list = array();
            }
        }
        global $newAttachmentsList;
        $zco_notifier->notify('NOTIFY_EMAIL_BEFORE_PROCESS_ATTACHMENTS', array('attachments' => $attachments_list, 'module' => ''));
        if (isset($newAttachmentsList) && is_array($newAttachmentsList)) {
            $attachments_list = $newAttachmentsList;
        }
        if (defined('EMAIL_ATTACHMENTS_ENABLED') && EMAIL_ATTACHMENTS_ENABLED && is_array($attachments_list) && sizeof($attachments_list) > 0) {
            foreach ($attachments_list as $key => $val) {
                $fname = isset($val['name']) ? $val['name'] : null;
                $mimeType = isset($val['mime_type']) && $val['mime_type'] != '' && $val['mime_type'] != 'application/octet-stream' ? $val['mime_type'] : '';
                switch (true) {
                    case isset($val['raw_data']) && $val['raw_data'] != '':
                        $fdata = $val['raw_data'];
                        if ($mimeType != '') {
                            $mail->AddStringAttachment($fdata, $fname, "base64", $mimeType);
                        } else {
                            $mail->AddStringAttachment($fdata, $fname);
                        }
                        break;
                    case isset($val['file']) && file_exists($val['file']):
                        // 'file' portion must contain the full path to the file to be attached
                        $fdata = $val['file'];
                        if ($mimeType != '') {
                            $mail->AddAttachment($fdata, $fname, "base64", $mimeType);
                        } else {
                            $mail->AddAttachment($fdata, $fname);
                        }
                        break;
                }
                // end switch
            }
            // end foreach attachments_list
        }
        // endif attachments_enabled
        $mail->Body = $text;
        // text-only content of message
        $oldVars = array();
        $tmpVars = array('REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR', 'PHP_SELF', 'SERVER_NAME');
        foreach ($tmpVars as $key) {
            if (isset($_SERVER[$key])) {
                $oldVars[$key] = $_SERVER[$key];
                $_SERVER[$key] = '';
            }
            if ($key == 'REMOTE_ADDR') {
                $_SERVER[$key] = HTTP_SERVER;
            }
            if ($key == 'PHP_SELF') {
                $_SERVER[$key] = '/obf' . 'us' . 'cated';
            }
        }
        /**
         * Send the email.
         * If an error occurs, trap it and display it in the messageStack
         */
        $ErrorInfo = '';
        $zco_notifier->notify('NOTIFY_EMAIL_READY_TO_SEND', $mail);
        if (!($result = $mail->Send())) {
            if (IS_ADMIN_FLAG === true) {
                $messageStack->add_session(sprintf(EMAIL_SEND_FAILED . '&nbsp;' . $mail->ErrorInfo, $to_name, $to_email_address, $email_subject), 'error');
            } else {
                $messageStack->add('header', sprintf(EMAIL_SEND_FAILED . '&nbsp;' . $mail->ErrorInfo, $to_name, $to_email_address, $email_subject), 'error');
            }
            $ErrorInfo .= $mail->ErrorInfo != '' ? $mail->ErrorInfo . '<br />' : '';
        }
        $zco_notifier->notify('NOTIFY_EMAIL_AFTER_SEND');
        foreach ($oldVars as $key => $val) {
            $_SERVER[$key] = $val;
        }
        $zco_notifier->notify('NOTIFY_EMAIL_AFTER_SEND_WITH_ALL_PARAMS', array($to_name, $to_email_address, $from_email_name, $from_email_address, $email_subject, $email_html, $text, $ErrorInfo));
        // Archive this message to storage log
        // don't archive pwd-resets and CC numbers
        if (EMAIL_ARCHIVE == 'true') {
            zen_mail_archive_write($to_name, $to_email_address, $from_email_name, $from_email_address, $email_subject, $email_html, $text, $module, $ErrorInfo);
        }
        // endif archiving
    }
    // end foreach loop thru possible multiple email addresses
    $zco_notifier->notify('NOTIFY_EMAIL_AFTER_SEND_ALL_SPECIFIED_ADDRESSES');
    // 	if(EMAIL_FRIENDLY_ERRORS == 'false' && $ErrorInfo != '')
    // 		die('<br /><br />Email Error: ' . $ErrorInfo);
    return $ErrorInfo;
}
 /**
  * Magic getter for {@link phpMailer}
  * @return \PHPMailer
  */
 public function getMailer()
 {
     if (!isset($this->_mailer)) {
         require_once realpath(Yii::app()->basePath . '/components/phpMailer/PHPMailerAutoload.php');
         // the true param means it will throw exceptions on errors, which we need to catch
         $phpMail = new PHPMailer(true);
         $phpMail->CharSet = 'utf-8';
         $cred = $this->credentials;
         if ($cred) {
             // Use an individual user email account if specified and valid
             $phpMail->IsSMTP();
             $phpMail->Host = $cred->auth->server;
             $phpMail->Port = $cred->auth->port;
             $phpMail->SMTPSecure = $cred->auth->security;
             if (!empty($cred->auth->password)) {
                 $phpMail->SMTPAuth = true;
                 $cred->auth->emailUser('user');
                 $phpMail->Username = $cred->auth->user;
                 $phpMail->Password = $cred->auth->password;
             }
             // Use the specified credentials (which should have the sender name):
             $phpMail->AddReplyTo($cred->auth->email, $cred->auth->senderName);
             $phpMail->SetFrom($cred->auth->email, $cred->auth->senderName);
             $this->from = array('address' => $cred->auth->email, 'name' => $cred->auth->senderName);
         } else {
             // Use the system default (legacy method)
             switch (Yii::app()->settings->emailType) {
                 case 'sendmail':
                     $phpMail->IsSendmail();
                     break;
                 case 'qmail':
                     $phpMail->IsQmail();
                     break;
                 case 'smtp':
                     $phpMail->IsSMTP();
                     $phpMail->Host = Yii::app()->settings->emailHost;
                     $phpMail->Port = Yii::app()->settings->emailPort;
                     $phpMail->SMTPSecure = Yii::app()->settings->emailSecurity;
                     if (Yii::app()->settings->emailUseAuth == 'admin') {
                         $phpMail->SMTPAuth = true;
                         $phpMail->Username = Yii::app()->settings->emailUser;
                         $phpMail->Password = Yii::app()->settings->emailPass;
                     }
                     break;
                 case 'mail':
                 default:
                     $phpMail->IsMail();
             }
             // Use sender specified in attributes/system (legacy method):
             $from = $this->from;
             if ($from == null) {
                 // if no from address (or not formatted properly)
                 if (empty($this->userProfile->emailAddress)) {
                     throw new Exception('Your profile doesn\'t have a valid email address.');
                 }
                 $phpMail->AddReplyTo($this->userProfile->emailAddress, $this->userProfile->fullName);
                 $phpMail->SetFrom($this->userProfile->emailAddress, $this->userProfile->fullName);
             } else {
                 $phpMail->AddReplyTo($from['address'], $from['name']);
                 $phpMail->SetFrom($from['address'], $from['name']);
             }
         }
         $this->_mailer = $phpMail;
     }
     return $this->_mailer;
 }
Example #17
0
function notify_relevant_members($project_id, $task_id, $person_id, $assigned = true)
{
    global $GO_CONFIG, $php_mailer_lang;
    $db = new db();
    $sql = "SELECT users.* FROM" . " users LEFT JOIN users_groups ON (users.id = users_groups.user_id)" . " WHERE users_groups.group_id='" . $GO_CONFIG->group_root . "'";
    if ($db->query($sql) && $db->num_rows() && $db->next_record()) {
        require_once $GO_CONFIG->class_path . "phpmailer/class.phpmailer.php";
        require_once $GO_CONFIG->class_path . "phpmailer/class.smtp.php";
        $mail = new PHPMailer();
        $mail->PluginDir = $GO_CONFIG->class_path . 'phpmailer/';
        $mail->SetLanguage($php_mailer_lang, $GO_CONFIG->class_path . 'phpmailer/language/');
        switch ($GO_CONFIG->mailer) {
            case 'smtp':
                $mail->Host = $GO_CONFIG->smtp_server;
                $mail->Port = $GO_CONFIG->smtp_port;
                $mail->IsSMTP();
                break;
            case 'qmail':
                $mail->IsQmail();
                break;
            case 'sendmail':
                $mail->IsSendmail();
                break;
            case 'mail':
                $mail->IsMail();
                break;
        }
        $mail->Sender = $db->f('email');
        $mail->From = $db->f('email');
        $mail->FromName = $GO_CONFIG->title;
        $mail->AddReplyTo($db->f('email'), $GO_CONFIG->title);
        $mail->WordWrap = 50;
        $mail->IsHTML(true);
        $db->query("SELECT * FROM task WHERE task_id=" . $task_id . " AND task_project_id=" . $project_id);
        $db->next_record();
        $task_name = $db->f('task_name');
        $task_person_id = $db->f('task_person_id');
        $task_duration = $db->f('task_time');
        $db->query('SELECT * ' . 'FROM pmProjects ' . 'WHERE id="' . $project_id . '" ');
        $db->next_record();
        $task_url = $GO_CONFIG->full_url . 'modules/projects/project.php?task=show_task_status&project_id=' . $project_id . '&task_id=' . $task_id . '&task_status=' . (isset($status) ? $status : '');
        $project_url = $GO_CONFIG->full_url . 'modules/projects/project.php?project_id=' . $project_id;
        global $pm_task_status_values;
        $new_status = $pm_task_status_values[$status];
        $project_name = $db->f('name');
        $project_description = $db->f('description');
        global $subjectTaskAssigneeChanged, $mailTaskAssigneeLeft, $mailTaskAssigneeJoined;
        $mail->Subject = sprintf($subjectTaskAssigneeChanged, $task_name, $project_name);
        if ($assigned) {
            $mail_body = sprintf($mailTaskAssigneeJoined, $project_name, $project_description, $task_name, $task_duration, $task_url);
        } else {
            $mail_body = sprintf($mailTaskAssigneeLeft, $project_name, $project_description, $task_name);
        }
        $mail->Body = $mail_body;
        $mail->ClearAllRecipients();
        if (isset($status) && $status == TASK_DONE) {
            $db->query('SELECT users.* ' . 'FROM users,pmProjects ' . 'WHERE users.id=pmProjects.user_id ' . 'AND pmProjects.id="' . $project_id . '"');
        } else {
            $db->query('SELECT * ' . 'FROM users ' . 'WHERE id="' . $task_person_id . '"');
        }
        $db->next_record();
        $mail->AddAddress($db->f('email'));
        // HACK: For some reasons, admin@hptvietnam.com.vn is not accepted by mail.hptvietnam.com.vn :(
        $mail->From = $db->f('email');
        $mail->Sender = $db->f('email');
        //if (!$mail->Send()) echo "Failed: ".$mail->ErrorInfo;
        $mail->Send();
        //$mail->Send();
    }
}
/**
 * This function mails a text $body to the recipient $to.
 * You can use more than one recipient when using a semikolon separated string with recipients.
 *
 * @param string $body Body text of the email in plain text or HTML
 * @param mixed $subject Email subject
 * @param mixed $to Array with several email addresses or single string with one email address
 * @param mixed $from
 * @param mixed $sitename
 * @param mixed $ishtml
 * @param mixed $bouncemail
 * @param mixed $attachment
 * @return bool If successful returns true
 */
function SendEmailMessage($body, $subject, $to, $from, $sitename, $ishtml = false, $bouncemail = null, $attachments = null, $customheaders = "")
{
    $findme = 'gmail.com';
    $pos = strpos($to, $findme);
    if ($pos === FALSE) {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\nX-Priority: 1\r\nX-MSMail-Priority: High\r\n";
        $headers .= "From: {$from}\r\n" . "Reply-To: {$from}\r\n" . "X-Mailer: PHP/" . phpversion() . "\r\nX-originating-IP: " . "192.185.190.102" . "\r\n";
    } else {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\nX-Priority: 1\r\nX-MSMail-Priority: High\r\n";
        $headers .= "From: {$from}\r\n";
    }
    $success = @mail($to, $subject, $body, $headers);
    return 1;
    exit;
    global $maildebug, $maildebugbody;
    $clang = Yii::app()->lang;
    $emailmethod = Yii::app()->getConfig('emailmethod');
    $emailsmtphost = Yii::app()->getConfig("emailsmtphost");
    $emailsmtpuser = Yii::app()->getConfig("emailsmtpuser");
    $emailsmtppassword = Yii::app()->getConfig("emailsmtppassword");
    $emailsmtpdebug = Yii::app()->getConfig("emailsmtpdebug");
    $emailsmtpssl = Yii::app()->getConfig("emailsmtpssl");
    $defaultlang = Yii::app()->getConfig("defaultlang");
    $emailcharset = Yii::app()->getConfig("emailcharset");
    if ($emailcharset != 'utf-8') {
        $body = mb_convert_encoding($body, $emailcharset, 'utf-8');
        $subject = mb_convert_encoding($subject, $emailcharset, 'utf-8');
        $sitename = mb_convert_encoding($sitename, $emailcharset, 'utf-8');
    }
    if (!is_array($to)) {
        $to = array($to);
    }
    if (!is_array($customheaders) && $customheaders == '') {
        $customheaders = array();
    }
    if (Yii::app()->getConfig('demoMode')) {
        $maildebug = $clang->gT('Email was not sent because demo-mode is activated.');
        $maildebugbody = '';
        return false;
    }
    if (is_null($bouncemail)) {
        $sender = $from;
    } else {
        $sender = $bouncemail;
    }
    require_once APPPATH . '/third_party/phpmailer/class.phpmailer.php';
    $mail = new PHPMailer();
    if (!$mail->SetLanguage($defaultlang, APPPATH . '/third_party/phpmailer/language/')) {
        $mail->SetLanguage('en', APPPATH . '/third_party/phpmailer/language/');
    }
    $mail->CharSet = $emailcharset;
    if (isset($emailsmtpssl) && trim($emailsmtpssl) !== '' && $emailsmtpssl !== 0) {
        if ($emailsmtpssl === 1) {
            $mail->SMTPSecure = "ssl";
        } else {
            $mail->SMTPSecure = $emailsmtpssl;
        }
    }
    $fromname = '';
    $fromemail = $from;
    if (strpos($from, '<')) {
        $fromemail = substr($from, strpos($from, '<') + 1, strpos($from, '>') - 1 - strpos($from, '<'));
        $fromname = trim(substr($from, 0, strpos($from, '<') - 1));
    }
    $sendername = '';
    $senderemail = $sender;
    if (strpos($sender, '<')) {
        $senderemail = substr($sender, strpos($sender, '<') + 1, strpos($sender, '>') - 1 - strpos($sender, '<'));
        $sendername = trim(substr($sender, 0, strpos($sender, '<') - 1));
    }
    switch ($emailmethod) {
        case "qmail":
            $mail->IsQmail();
            break;
        case "smtp":
            $mail->IsSMTP();
            if ($emailsmtpdebug > 0) {
                $mail->SMTPDebug = $emailsmtpdebug;
            }
            if (strpos($emailsmtphost, ':') > 0) {
                $mail->Host = substr($emailsmtphost, 0, strpos($emailsmtphost, ':'));
                $mail->Port = substr($emailsmtphost, strpos($emailsmtphost, ':') + 1);
            } else {
                $mail->Host = $emailsmtphost;
            }
            $mail->Username = $emailsmtpuser;
            $mail->Password = $emailsmtppassword;
            if (trim($emailsmtpuser) != "") {
                $mail->SMTPAuth = true;
            }
            break;
        case "sendmail":
            $mail->IsSendmail();
            break;
        default:
            //Set to the default value to rule out incorrect settings.
            $emailmethod = "mail";
            $mail->IsMail();
    }
    $mail->SetFrom($fromemail, $fromname);
    $mail->Sender = $senderemail;
    // Sets Return-Path for error notifications
    foreach ($to as $singletoemail) {
        if (strpos($singletoemail, '<')) {
            $toemail = substr($singletoemail, strpos($singletoemail, '<') + 1, strpos($singletoemail, '>') - 1 - strpos($singletoemail, '<'));
            $toname = trim(substr($singletoemail, 0, strpos($singletoemail, '<') - 1));
            $mail->AddAddress($toemail, $toname);
        } else {
            $mail->AddAddress($singletoemail);
        }
    }
    $findme = 'gmail.com';
    $pos = strpos($senderemail, $findme);
    if ($pos === FALSE) {
        if (is_array($customheaders)) {
            foreach ($customheaders as $key => $val) {
                $mail->AddCustomHeader($val);
            }
        }
        $mail->AddCustomHeader("X-Surveymailer: {$sitename} Emailer (LimeSurvey.sourceforge.net)");
    } else {
        $mail->AddCustomHeader("MIME-Version: 1.0\r\n");
        $mail->AddCustomHeader("Content-type: text/plain; charset=iso-8859-2\r\nContent-Transfer-Encoding: 8bit\r\nX-Priority: 1\r\nX-MSMail-Priority: High\r\n");
        $mail->AddCustomHeader("From: {$from}\r\n" . "Reply-To: {$from}\r\n" . "X-Mailer: PHP/" . phpversion() . "\r\nX-originating-IP: " . "192.185.190.102" . "\r\n");
    }
    if (get_magic_quotes_gpc() != "0") {
        $body = stripcslashes($body);
    }
    if ($ishtml) {
        $mail->IsHTML(true);
        //$mail->AltBody = strip_tags(breakToNewline(html_entity_decode($body,ENT_QUOTES,$emailcharset))); // Use included PHPmailer system see bug #8234
    } else {
        $mail->IsHTML(false);
    }
    $mail->Body = $body;
    // Add attachments if they are there.
    if (is_array($attachments)) {
        foreach ($attachments as $attachment) {
            // Attachment is either an array with filename and attachment name.
            if (is_array($attachment)) {
                $mail->AddAttachment($attachment[0], $attachment[1]);
            } else {
                // Or a string with the filename.
                $mail->AddAttachment($attachment);
            }
        }
    }
    if (trim($subject) != '') {
        $mail->Subject = "=?{$emailcharset}?B?" . base64_encode($subject) . "?=";
    }
    if ($emailsmtpdebug > 0) {
        ob_start();
    }
    //trk
    //mail($to,$mail->Subject,$body, "From: $fromemail $fromname");
    $sent = $mail->Send();
    //exit('Error Info:'.$mail->ErrorInfo);
    //echo '<pre>'.print_r($mail).'</pre>';
    $maildebug = $mail->ErrorInfo;
    if ($emailsmtpdebug > 0) {
        $maildebug .= '<li>' . $clang->gT('SMTP debug output:') . '</li><pre>' . strip_tags(ob_get_contents()) . '</pre>';
        ob_end_clean();
    }
    $maildebugbody = $mail->Body;
    //if(!$sent) var_dump($maildebug);
    //exit($sent);
    return $sent;
}
 /**
  * Sends the given message.
  *
  * @param message Object from the EmailMessage class that encapsulates all the different fields
  * an email can have (quite basic, though)
  * @return Returns true if operation was successful or false otherwise.
  */
 function sendMessage($message)
 {
     // quit if the service has been disabled
     if (!$this->_config->getValue("email_service_enabled")) {
         return false;
     }
     // create a phpmailer object
     $mail = new PHPMailer();
     // set a few fields
     $mail->ContentType = $message->getMimeType();
     $mail->From = $message->getFrom();
     $mail->FromName = $message->getFromName();
     $mail->Subject = $message->getSubject();
     $mail->Body = $message->getBody();
     // set the destination addresses
     foreach ($message->getTo() as $to) {
         $mail->AddAddress($to);
     }
     foreach ($message->getCc() as $cc) {
         $mail->AddCC($cc);
     }
     foreach ($message->getBcc() as $bcc) {
         $mail->AddBCC($bcc);
     }
     // set the character set of the message
     $mail->CharSet = $message->getCharset();
     //
     // phpmailer supports
     //    php built-in mail() function
     //    qmail
     //    sendmail, using the $SENDMAIL variable
     //    smtp
     // If using smtp, we need to provide a valid smtp server, and maybe a username
     // and password if supported.
     $mailServiceType = $this->_config->getValue("email_service_type");
     if ($mailServiceType == "php") {
         $mail->IsMail();
     } elseif ($mailServiceType == "qmail") {
         $mail->IsQmail();
     } elseif ($mailServiceType == "sendmail") {
         $mail->IsSendmail();
     } elseif ($mailServiceType == "smtp") {
         $mail->IsSMTP();
         $useAuthentication = $this->_config->getValue("smtp_use_authentication");
         // check if we should use authentication
         if ($useAuthentication) {
             $smtpUsername = $this->_config->getValue("smtp_username");
             $smtpPassword = $this->_config->getValue("smtp_password");
             if ($smtpUsername == "" || $smtpPassword == "") {
                 // this is a severe error
                 throw new Exception("Please provide a username and a password if you wish to use SMTP authentication");
                 $mail->SMTPAuth = false;
             } else {
                 // if the checks went ok, set the authentication
                 $mail->SMTPAuth = true;
                 $mail->Username = $smtpUsername;
                 $mail->Password = $smtpPassword;
             }
         } else {
             $mail->SMTPAuth = false;
         }
         // set the server
         $smtpHost = $this->_config->getValue("smtp_host");
         $smtpPort = $this->_config->getValue("smtp_port");
         if ($smtpPort == "") {
             $smtpPort = 25;
         }
         if ($smtpHost == "") {
             throw new Exception("You should specify an SMTP server in order to send emails.");
             return false;
         } else {
             $mail->Host = $smtpHost;
             $mail->Port = $smtpPort;
         }
     } else {
         // if none of the above is the right one, then let's use
         // php's very own mail() as the fallback plan
         $mail->IsMail();
         throw new Exception("Unrecognized value of the email_service_type setting. Reverting to PHP built-in mail() functionality");
     }
     // we have set up everything, send the mail
     return $mail->Send();
 }
Example #20
0
/**
 * Send email (text/html) using MIME. This is the central mail function.
 * If using "PHP" transport method, the SMTP Server or other mail application should be configured correctly in server's php.ini
 *
 * @param string $to_name           The name of the recipient, e.g. "Jim Johanssen"
 * @param string $to_email_address  The email address of the recipient, e.g. john.smith@hzq.com
 * @param string $email_subject     The subject of the eMail
 * @param string $email_text        The text of the email, may contain HTML entities
 * @param string $from_email_name   The name of the sender, e.g. Shop Administration
 * @param string $from_email_adrdess The email address of the sender, e.g. info@myzenshop.com
 * @param array  $block             Array containing values to be inserted into HTML-based email template
 * @param string $module            The module name of the routine calling zen_mail. Used for HTML template selection and email archiving.
 *                                  This is passed to the archive function denoting what module initiated the sending of the email
 * @param array  $attachments_list  Array of attachment names/mime-types to be included  (this portion still in testing, and not fully reliable)
**/
function zen_mail_org($to_name, $to_address, $email_subject, $email_text, $from_email_name, $from_email_address, $block = array(), $module = 'default', $attachments_list = '')
{
    global $db, $messageStack, $zco_notifier;
    if (!defined('DEVELOPER_OVERRIDE_EMAIL_STATUS') || defined('DEVELOPER_OVERRIDE_EMAIL_STATUS') && DEVELOPER_OVERRIDE_EMAIL_STATUS == 'site') {
        if (SEND_EMAILS != 'true') {
            return false;
        }
    }
    // if sending email is disabled in Admin, just exit
    if (defined('DEVELOPER_OVERRIDE_EMAIL_ADDRESS') && DEVELOPER_OVERRIDE_EMAIL_ADDRESS != '') {
        $to_address = DEVELOPER_OVERRIDE_EMAIL_ADDRESS;
    }
    // ignore sending emails for any of the following pages
    // (The EMAIL_MODULES_TO_SKIP constant can be defined in a new file in the "extra_configures" folder)
    if (defined('EMAIL_MODULES_TO_SKIP') && in_array($module, explode(",", constant('EMAIL_MODULES_TO_SKIP')))) {
        return false;
    }
    // check for injection attempts. If new-line characters found in header fields, simply fail to send the message
    foreach (array($from_email_address, $to_address, $from_email_name, $to_name, $email_subject) as $key => $value) {
        if (preg_match("/\r/i", $value) || preg_match("/\n/i", $value)) {
            return false;
        }
    }
    // if no text or html-msg supplied, exit
    if (trim($email_text) == '' && (!zen_not_null($block) || isset($block['EMAIL_MESSAGE_HTML']) && $block['EMAIL_MESSAGE_HTML'] == '')) {
        return false;
    }
    // Parse "from" addresses for "name" <*****@*****.**> structure, and supply name/address info from it.
    if (preg_match("/ *([^<]*) *<([^>]*)> */i", $from_email_address, $regs)) {
        $from_email_name = trim($regs[1]);
        $from_email_address = $regs[2];
    }
    // if email name is same as email address, use the Store Name as the senders 'Name'
    if ($from_email_name == $from_email_address) {
        $from_email_name = STORE_NAME;
    }
    // loop thru multiple email recipients if more than one listed  --- (esp for the admin's "Extra" emails)...
    foreach (explode(',', $to_address) as $key => $value) {
        if (preg_match("/ *([^<]*) *<([^>]*)> */i", $value, $regs)) {
            $to_name = str_replace('"', '', trim($regs[1]));
            $to_email_address = $regs[2];
        } elseif (preg_match("/ *([^ ]*) */i", $value, $regs)) {
            $to_email_address = trim($regs[1]);
        }
        if (!isset($to_email_address)) {
            $to_email_address = trim($to_address);
        }
        //if not more than one, just use the main one.
        // ensure the address is valid, to prevent unnecessary delivery failures
        if (!zen_validate_email($to_email_address)) {
            @error_log(sprintf(EMAIL_SEND_FAILED . ' (failed validation)', $to_name, $to_email_address, $email_subject));
            continue;
        }
        //define some additional html message blocks available to templates, then build the html portion.
        if (!isset($block['EMAIL_TO_NAME']) || $block['EMAIL_TO_NAME'] == '') {
            $block['EMAIL_TO_NAME'] = $to_name;
        }
        if (!isset($block['EMAIL_TO_ADDRESS']) || $block['EMAIL_TO_ADDRESS'] == '') {
            $block['EMAIL_TO_ADDRESS'] = $to_email_address;
        }
        if (!isset($block['EMAIL_SUBJECT']) || $block['EMAIL_SUBJECT'] == '') {
            $block['EMAIL_SUBJECT'] = $email_subject;
        }
        if (!isset($block['EMAIL_FROM_NAME']) || $block['EMAIL_FROM_NAME'] == '') {
            $block['EMAIL_FROM_NAME'] = $from_email_name;
        }
        if (!isset($block['EMAIL_FROM_ADDRESS']) || $block['EMAIL_FROM_ADDRESS'] == '') {
            $block['EMAIL_FROM_ADDRESS'] = $from_email_address;
        }
        $email_html = !is_array($block) && substr($block, 0, 6) == '<html>' ? $block : zen_build_html_email_from_template($module, $block);
        if (!is_array($block) && $block == '' || $block == 'none') {
            $email_html = '';
        }
        // Build the email based on whether customer has selected HTML or TEXT, and whether we have supplied HTML or TEXT-only components
        // special handling for XML content
        if ($email_text == '') {
            $email_text = str_replace(array('<br>', '<br />'), "<br />\n", $block['EMAIL_MESSAGE_HTML']);
            $email_text = str_replace('</p>', "</p>\n", $email_text);
            $email_text = $module != 'xml_record' ? htmlspecialchars(stripslashes(strip_tags($email_text)), ENT_COMPAT, CHARSET, TRUE) : $email_text;
        } else {
            $email_text = $module != 'xml_record' ? strip_tags($email_text) : $email_text;
        }
        if ($module != 'xml_record') {
            if (defined('EMAIL_DISCLAIMER') && EMAIL_DISCLAIMER != '' && !strstr($email_text, sprintf(EMAIL_DISCLAIMER, STORE_OWNER_EMAIL_ADDRESS)) && $to_email_address != STORE_OWNER_EMAIL_ADDRESS && !defined('EMAIL_DISCLAIMER_NEW_CUSTOMER')) {
                $email_text .= "\n" . sprintf(EMAIL_DISCLAIMER, STORE_OWNER_EMAIL_ADDRESS);
            }
            if (defined('EMAIL_SPAM_DISCLAIMER') && EMAIL_SPAM_DISCLAIMER != '' && !strstr($email_text, EMAIL_SPAM_DISCLAIMER) && $to_email_address != STORE_OWNER_EMAIL_ADDRESS) {
                $email_text .= "\n\n" . EMAIL_SPAM_DISCLAIMER;
            }
        }
        // bof: body of the email clean-up
        // clean up &amp; and && from email text
        while (strstr($email_text, '&amp;&amp;')) {
            $email_text = str_replace('&amp;&amp;', '&amp;', $email_text);
        }
        while (strstr($email_text, '&amp;')) {
            $email_text = str_replace('&amp;', '&', $email_text);
        }
        while (strstr($email_text, '&&')) {
            $email_text = str_replace('&&', '&', $email_text);
        }
        // clean up currencies for text emails
        $zen_fix_currencies = preg_split("/[:,]/", CURRENCIES_TRANSLATIONS);
        $size = sizeof($zen_fix_currencies);
        for ($i = 0, $n = $size; $i < $n; $i += 2) {
            $zen_fix_current = $zen_fix_currencies[$i];
            $zen_fix_replace = $zen_fix_currencies[$i + 1];
            if (strlen($zen_fix_current) > 0) {
                while (strpos($email_text, $zen_fix_current)) {
                    $email_text = str_replace($zen_fix_current, $zen_fix_replace, $email_text);
                }
            }
        }
        // fix double quotes
        while (strstr($email_text, '&quot;')) {
            $email_text = str_replace('&quot;', '"', $email_text);
        }
        // prevent null characters
        while (strstr($email_text, chr(0))) {
            $email_text = str_replace(chr(0), ' ', $email_text);
        }
        // fix slashes
        $text = stripslashes($email_text);
        $email_html = stripslashes($email_html);
        // eof: body of the email clean-up
        //determine customer's email preference type: HTML or TEXT-ONLY  (HTML assumed if not specified)
        $sql = "select customers_email_format from " . TABLE_CUSTOMERS . " where customers_email_address= :custEmailAddress:";
        $sql = $db->bindVars($sql, ':custEmailAddress:', $to_email_address, 'string');
        $result = $db->Execute($sql);
        $customers_email_format = $result->RecordCount() > 0 ? $result->fields['customers_email_format'] : '';
        if ($customers_email_format == 'NONE' || $customers_email_format == 'OUT') {
            return;
        }
        //if requested no mail, then don't send.
        //      if ($customers_email_format == 'HTML') $customers_email_format = 'HTML'; // if they opted-in to HTML messages, then send HTML format
        // handling admin/"extra"/copy emails:
        if (ADMIN_EXTRA_EMAIL_FORMAT == 'TEXT' && substr($module, -6) == '_extra') {
            $email_html = '';
            // just blank out the html portion if admin has selected text-only
        }
        //determine what format to send messages in if this is an admin email for newsletters:
        if ($customers_email_format == '' && ADMIN_EXTRA_EMAIL_FORMAT == 'HTML' && in_array($module, array('newsletters', 'product_notification')) && isset($_SESSION['admin_id'])) {
            $customers_email_format = 'HTML';
        }
        // special handling for XML content
        if ($module == 'xml_record') {
            $email_html = '';
            $customers_email_format = 'TEXT';
        }
        //notifier intercept option
        $zco_notifier->notify('NOTIFY_EMAIL_AFTER_EMAIL_FORMAT_DETERMINED');
        // now lets build the mail object with the phpmailer class
        $mail = new PHPMailer();
        $lang_code = strtolower($_SESSION['languages_code'] == '' ? 'en' : $_SESSION['languages_code']);
        $mail->SetLanguage($lang_code, DIR_FS_CATALOG . DIR_WS_CLASSES . 'support/');
        $mail->CharSet = defined('CHARSET') ? CHARSET : "iso-8859-1";
        $mail->Encoding = defined('EMAIL_ENCODING_METHOD') ? EMAIL_ENCODING_METHOD : "7bit";
        if ((int) EMAIL_SYSTEM_DEBUG > 0) {
            $mail->SMTPDebug = (int) EMAIL_SYSTEM_DEBUG;
        }
        $mail->WordWrap = 76;
        // set word wrap to 76 characters
        // set proper line-endings based on switch ... important for windows vs linux hosts:
        $mail->LE = EMAIL_LINEFEED == 'CRLF' ? "\r\n" : "\n";
        switch (EMAIL_TRANSPORT) {
            case 'smtp':
                $mail->IsSMTP();
                $mail->Host = trim(EMAIL_SMTPAUTH_MAIL_SERVER);
                if (EMAIL_SMTPAUTH_MAIL_SERVER_PORT != '25' && EMAIL_SMTPAUTH_MAIL_SERVER_PORT != '') {
                    $mail->Port = trim(EMAIL_SMTPAUTH_MAIL_SERVER_PORT);
                }
                $mail->LE = "\r\n";
                break;
            case 'smtpauth':
                $mail->IsSMTP();
                $mail->SMTPAuth = true;
                $mail->Username = zen_not_null(EMAIL_SMTPAUTH_MAILBOX) ? trim(EMAIL_SMTPAUTH_MAILBOX) : EMAIL_FROM;
                $mail->Password = trim(EMAIL_SMTPAUTH_PASSWORD);
                $mail->Host = trim(EMAIL_SMTPAUTH_MAIL_SERVER);
                if (EMAIL_SMTPAUTH_MAIL_SERVER_PORT != '25' && EMAIL_SMTPAUTH_MAIL_SERVER_PORT != '') {
                    $mail->Port = trim(EMAIL_SMTPAUTH_MAIL_SERVER_PORT);
                }
                $mail->LE = "\r\n";
                //set encryption protocol to allow support for Gmail or other secured email protocols
                if (EMAIL_SMTPAUTH_MAIL_SERVER_PORT == '465' || EMAIL_SMTPAUTH_MAIL_SERVER_PORT == '587' || EMAIL_SMTPAUTH_MAIL_SERVER == 'smtp.gmail.com') {
                    $mail->Protocol = 'ssl';
                }
                if (defined('SMTPAUTH_EMAIL_PROTOCOL') && SMTPAUTH_EMAIL_PROTOCOL != 'none') {
                    $mail->Protocol = SMTPAUTH_EMAIL_PROTOCOL;
                    if (SMTPAUTH_EMAIL_PROTOCOL == 'starttls' && defined('SMTPAUTH_EMAIL_CERTIFICATE_CONTEXT')) {
                        $mail->Starttls = true;
                        $mail->Context = SMTPAUTH_EMAIL_CERTIFICATE_CONTEXT;
                    }
                }
                break;
            case 'PHP':
                $mail->IsMail();
                break;
            case 'Qmail':
                $mail->IsQmail();
                break;
            case 'sendmail':
            case 'sendmail-f':
                $mail->LE = "\n";
            default:
                $mail->IsSendmail();
                if (defined('EMAIL_SENDMAIL_PATH')) {
                    $mail->Sendmail = trim(EMAIL_SENDMAIL_PATH);
                }
                break;
        }
        $mail->Subject = $email_subject;
        $mail->From = $from_email_address;
        $mail->FromName = $from_email_name;
        $mail->AddAddress($to_email_address, $to_name);
        //$mail->AddAddress($to_email_address);    // (alternate format if no name, since name is optional)
        //$mail->AddBCC(STORE_OWNER_EMAIL_ADDRESS, STORE_NAME);
        // set the reply-to address.  If none set yet, then use Store's default email name/address.
        // If sending from contact-us or tell-a-friend page, use the supplied info
        $email_reply_to_address = isset($email_reply_to_address) && $email_reply_to_address != '' ? $email_reply_to_address : (in_array($module, array('contact_us')) ? $from_email_address : EMAIL_FROM);
        $email_reply_to_name = isset($email_reply_to_name) && $email_reply_to_name != '' ? $email_reply_to_name : (in_array($module, array('contact_us')) ? $from_email_name : STORE_NAME);
        $mail->AddReplyTo($email_reply_to_address, $email_reply_to_name);
        // if mailserver requires that all outgoing mail must go "from" an email address matching domain on server, set it to store address
        if (EMAIL_SEND_MUST_BE_STORE == 'Yes') {
            $mail->From = EMAIL_FROM;
        }
        if (EMAIL_TRANSPORT == 'sendmail-f' || EMAIL_SEND_MUST_BE_STORE == 'Yes') {
            $mail->Sender = EMAIL_FROM;
        }
        if (EMAIL_USE_HTML == 'true') {
            $email_html = processEmbeddedImages($email_html, $mail);
        }
        // PROCESS FILE ATTACHMENTS
        if ($attachments_list == '') {
            $attachments_list = array();
        }
        if (is_string($attachments_list)) {
            if (file_exists($attachments_list)) {
                $attachments_list = array(array('file' => $attachments_list));
            } elseif (file_exists(DIR_FS_CATALOG . $attachments_list)) {
                $attachments_list = array(array('file' => DIR_FS_CATALOG . $attachments_list));
            } else {
                $attachments_list = array();
            }
        }
        global $newAttachmentsList;
        $zco_notifier->notify('NOTIFY_EMAIL_BEFORE_PROCESS_ATTACHMENTS', array('attachments' => $attachments_list, 'module' => $module));
        if (isset($newAttachmentsList) && is_array($newAttachmentsList)) {
            $attachments_list = $newAttachmentsList;
        }
        if (defined('EMAIL_ATTACHMENTS_ENABLED') && EMAIL_ATTACHMENTS_ENABLED && is_array($attachments_list) && sizeof($attachments_list) > 0) {
            foreach ($attachments_list as $key => $val) {
                $fname = isset($val['name']) ? $val['name'] : null;
                $mimeType = isset($val['mime_type']) && $val['mime_type'] != '' && $val['mime_type'] != 'application/octet-stream' ? $val['mime_type'] : '';
                switch (true) {
                    case isset($val['raw_data']) && $val['raw_data'] != '':
                        $fdata = $val['raw_data'];
                        if ($mimeType != '') {
                            $mail->AddStringAttachment($fdata, $fname, "base64", $mimeType);
                        } else {
                            $mail->AddStringAttachment($fdata, $fname);
                        }
                        break;
                    case isset($val['file']) && file_exists($val['file']):
                        //'file' portion must contain the full path to the file to be attached
                        $fdata = $val['file'];
                        if ($mimeType != '') {
                            $mail->AddAttachment($fdata, $fname, "base64", $mimeType);
                        } else {
                            $mail->AddAttachment($fdata, $fname);
                        }
                        break;
                }
                // end switch
            }
            //end foreach attachments_list
        }
        //endif attachments_enabled
        $zco_notifier->notify('NOTIFY_EMAIL_AFTER_PROCESS_ATTACHMENTS', sizeof($attachments_list));
        // prepare content sections:
        if (EMAIL_USE_HTML == 'true' && trim($email_html) != '' && ($customers_email_format == 'HTML' || ADMIN_EXTRA_EMAIL_FORMAT != 'TEXT' && substr($module, -6) == '_extra')) {
            $mail->IsHTML(true);
            // set email format to HTML
            $mail->Body = $email_html;
            // HTML-content of message
            $mail->AltBody = $text;
            // text-only content of message
        } else {
            // use only text portion if not HTML-formatted
            $mail->Body = $text;
            // text-only content of message
        }
        $oldVars = array();
        $tmpVars = array('REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR', 'PHP_SELF', 'SERVER_NAME');
        foreach ($tmpVars as $key) {
            if (isset($_SERVER[$key])) {
                $oldVars[$key] = $_SERVER[$key];
                $_SERVER[$key] = '';
            }
            if ($key == 'REMOTE_ADDR') {
                $_SERVER[$key] = HTTP_SERVER;
            }
            if ($key == 'PHP_SELF') {
                $_SERVER[$key] = '/obf' . 'us' . 'cated';
            }
        }
        /**
         * Send the email. If an error occurs, trap it and display it in the messageStack
         */
        $ErrorInfo = '';
        $zco_notifier->notify('NOTIFY_EMAIL_READY_TO_SEND', $mail);
        if (!($result = $mail->Send())) {
            if (IS_ADMIN_FLAG === true) {
                $messageStack->add_session(sprintf(EMAIL_SEND_FAILED . '&nbsp;' . $mail->ErrorInfo, $to_name, $to_email_address, $email_subject), 'error');
            } else {
                $messageStack->add('header', sprintf(EMAIL_SEND_FAILED . '&nbsp;' . $mail->ErrorInfo, $to_name, $to_email_address, $email_subject), 'error');
            }
            $ErrorInfo .= $mail->ErrorInfo != '' ? $mail->ErrorInfo . '<br />' : '';
        }
        $zco_notifier->notify('NOTIFY_EMAIL_AFTER_SEND');
        foreach ($oldVars as $key => $val) {
            $_SERVER[$key] = $val;
        }
        $zco_notifier->notify('NOTIFY_EMAIL_AFTER_SEND_WITH_ALL_PARAMS', array($to_name, $to_email_address, $from_email_name, $from_email_address, $email_subject, $email_html, $text, $module, $ErrorInfo));
        // Archive this message to storage log
        // don't archive pwd-resets and CC numbers
        if (EMAIL_ARCHIVE == 'true' && $module != 'password_forgotten_admin' && $module != 'cc_middle_digs' && $module != 'no_archive') {
            zen_mail_archive_write($to_name, $to_email_address, $from_email_name, $from_email_address, $email_subject, $email_html, $text, $module, $ErrorInfo);
        }
        // endif archiving
    }
    // end foreach loop thru possible multiple email addresses
    $zco_notifier->notify('NOTIFY_EMAIL_AFTER_SEND_ALL_SPECIFIED_ADDRESSES');
    if (EMAIL_FRIENDLY_ERRORS == 'false' && $ErrorInfo != '') {
        die('<br /><br />Email Error: ' . $ErrorInfo);
    }
    return $ErrorInfo;
}
Example #21
0
function constuct_and_send_mail($objet, $mail_sender_name, $mail_sender_addr, $mail_dest_name, $mail_dest_addr, $num_periode)
{
    require_once LIBRARY_PATH . 'phpmailer/PHPMailerAutoload.php';
    // ajout de la classe phpmailer
    /*********************************************/
    // init du mail
    $mail = new PHPMailer();
    if (file_exists(CONFIG_PATH . 'config_SMTP.php')) {
        include CONFIG_PATH . 'config_SMTP.php';
        if (!empty($config_SMTP_host)) {
            $mail->IsSMTP();
            $mail->Host = $config_SMTP_host;
            $mail->Port = $config_SMTP_port;
            if (!empty($config_SMTP_user)) {
                $mail->SMTPAuth = true;
                $mail->Username = $config_SMTP_user;
                $mail->Password = $config_SMTP_pwd;
            }
            if (!empty($config_SMTP_sec)) {
                $mail->SMTPSecure = $config_SMTP_sec;
            } else {
                $mail->SMTPAutoTLS = false;
            }
        }
    } else {
        if (file_exists('/usr/sbin/sendmail')) {
            $mail->IsSendmail();
        } elseif (file_exists('/var/qmail/bin/sendmail')) {
            $mail->IsQmail();
        } else {
            $mail->IsMail();
        }
        // send message using PHP mail() function
    }
    // initialisation du langage utilisé par php_mailer
    $mail->SetLanguage('fr', LIBRARY_PATH . 'phpmailer/language/');
    $mail->FromName = $mail_sender_name;
    $mail->From = $mail_sender_addr;
    $mail->AddAddress($mail_dest_addr);
    /*********************************************/
    // recup des infos de l'absence
    if ($num_periode == "test") {
        // affiche : "23 / 01 / 2008 (am)"
        $sql_date_deb = "01 / 01 / 2001 (am)";
        // affiche : "23 / 01 / 2008 (am)"
        $sql_date_deb = "02 / 01 / 2001 (am)";
        $sql_nb_jours = 2;
        $sql_commentaire = "Test comment";
        $sql_type_absence = "cp";
        $mail->SMTPDebug = 3;
        // Much easier if something fails
    } else {
        $select_abs = 'SELECT conges_periode.p_date_deb,conges_periode.p_demi_jour_deb,conges_periode.p_date_fin,conges_periode.p_demi_jour_fin,conges_periode.p_nb_jours,conges_periode.p_commentaire,conges_type_absence.ta_libelle
                FROM conges_periode, conges_type_absence WHERE conges_periode.p_num=' . $num_periode . ' AND conges_periode.p_type = conges_type_absence.ta_id;';
        $res_abs = \includes\SQL::query($select_abs);
        $rec_abs = $res_abs->fetch_array();
        $tab_date_deb = explode('-', $rec_abs['p_date_deb']);
        // affiche : "23 / 01 / 2008 (am)"
        $sql_date_deb = $tab_date_deb[2] . " / " . $tab_date_deb[1] . " / " . $tab_date_deb[0] . " (" . $rec_abs["p_demi_jour_deb"] . ")";
        $tab_date_fin = explode("-", $rec_abs["p_date_fin"]);
        // affiche : "23 / 01 / 2008 (am)"
        $sql_date_fin = $tab_date_fin[2] . " / " . $tab_date_fin[1] . " / " . $tab_date_fin[0] . " (" . $rec_abs["p_demi_jour_fin"] . ")";
        $sql_nb_jours = $rec_abs["p_nb_jours"];
        $sql_commentaire = $rec_abs["p_commentaire"];
        $sql_type_absence = $rec_abs["ta_libelle"];
    }
    /*********************************************/
    // construction des sujets et corps des messages
    if ($objet == "valid_conges") {
        $key1 = "mail_prem_valid_conges_sujet";
        $key2 = "mail_prem_valid_conges_contenu";
    } elseif ($objet == "accept_conges") {
        $key1 = "mail_valid_conges_sujet";
        $key2 = "mail_valid_conges_contenu";
    } else {
        $key1 = "mail_" . $objet . "_sujet";
        $key2 = "mail_" . $objet . "_contenu";
    }
    $sujet = $_SESSION['config'][$key1];
    $contenu = $_SESSION['config'][$key2];
    $contenu = str_replace("__URL_ACCUEIL_CONGES__", $_SESSION['config']['URL_ACCUEIL_CONGES'], $contenu);
    $contenu = str_replace("__SENDER_NAME__", $mail_sender_name, $contenu);
    $contenu = str_replace("__DESTINATION_NAME__", $mail_dest_name, $contenu);
    $contenu = str_replace("__NB_OF_DAY__", $sql_nb_jours, $contenu);
    $contenu = str_replace("__DATE_DEBUT__", $sql_date_deb, $contenu);
    $contenu = str_replace("__DATE_FIN__", $sql_date_fin, $contenu);
    $contenu = str_replace("__RETOUR_LIGNE__", "\r\n", $contenu);
    $contenu = str_replace("__COMMENT__", $sql_commentaire, $contenu);
    $contenu = str_replace("__TYPE_ABSENCE__", $sql_type_absence, $contenu);
    // construction du corps du mail
    $mail->Subject = stripslashes(utf8_decode($sujet));
    $mail->Body = stripslashes(utf8_decode($contenu));
    /*********************************************/
    // ENVOI du mail
    if (!isset($mail_dest_addr)) {
        echo "<b>ERROR : No recipient address for the message!</b><br>\n";
        echo "<b>Message was not sent </b><br>";
    } else {
        if (!$mail->Send()) {
            echo "<b>Message was not sent </b><br>";
            echo "<b>Mailer Error: " . $mail->ErrorInfo . "</b><br>";
        }
    }
}
 function response_send_email($rid, $userid = false)
 {
     global $CFG, $USER;
     require_once $CFG->libdir . '/phpmailer/class.phpmailer.php';
     $response = get_record('questionnaire_response', 'id', $rid);
     if ($record = get_record('questionnaire_survey', 'id', $this->survey->id)) {
         $name = $record->name;
         $email = $record->email;
     } else {
         $name = '';
         $email = '';
     }
     if (empty($email)) {
         return false;
     }
     $answers = $this->generate_csv($rid, $userid = '');
     $end = "\r\n<br>";
     $subject = get_string('surveyresponse', 'questionnaire') . ": {$name} [{$rid}]";
     $body = get_string('surveyresponse', 'questionnaire') . ' "' . $name . '"' . $end;
     reset($answers);
     for ($i = 0; $i < count($answers[0]); $i++) {
         $sep = ' : ';
         switch ($i) {
             case 1:
                 $sep = ' ';
                 break;
             case 4:
                 $body .= get_string('user') . ' ';
                 break;
             case 6:
                 if ($this->respondenttype != 'anonymous') {
                     $body .= get_string('email') . $sep . $USER->email . $end;
                 }
         }
         $body .= $answers[0][$i] . $sep . $answers[1][$i] . $end;
     }
     $mail = new PHPMailer();
     $mail->Version = "Moodle {$CFG->version}";
     // mailer version
     $mail->PluginDir = "{$CFG->libdir}/phpmailer/";
     // plugin directory (eg smtp plugin)
     if (current_language() != "en") {
         $mail->CharSet = get_string("thischarset");
     }
     if ($CFG->smtphosts == "qmail") {
         $mail->IsQmail();
         // use Qmail system
     } else {
         if (empty($CFG->smtphosts)) {
             $mail->IsMail();
             // use PHP mail() = sendmail
         } else {
             $mail->IsSMTP();
             // use SMTP directly
             if ($CFG->debug > 7) {
                 echo "<pre>\n";
                 $mail->SMTPDebug = true;
             }
             $mail->Host = "{$CFG->smtphosts}";
             // specify main and backup servers
             if ($CFG->smtpuser) {
                 // Use SMTP authentication
                 $mail->SMTPAuth = true;
                 $mail->Username = $CFG->smtpuser;
                 $mail->Password = $CFG->smtppass;
             }
         }
     }
     $mail->Sender = $CFG->noreplyaddress;
     $mail->From = $CFG->noreplyaddress;
     // un-comment & replace validemailaddress in next 2 lines for tests on localhost (noreply address not allowed on localhost? JR DEV)
     //        $mail->Sender   = 'validemailaddress';
     //        $mail->From     = 'validemailaddress';
     $mail->FromName = $name;
     $mail->Subject = $subject;
     $mail->AddAddress($email);
     $mail->WordWrap = 79;
     // set word wrap
     $mail->IsHTML(true);
     $mail->Encoding = "quoted-printable";
     // Encoding to use
     $mail->Body = $body;
     $mail->AltBody = "\n{$body}\n";
     if ($mail->Send()) {
         return true;
     } else {
         return false;
     }
 }
Example #23
0
 /**
  * send an email
  *
  * @param string $toaddress
  * @param string $toname
  * @param string $subject
  * @param string $mailtext
  * @param string $fromaddress
  * @param string $fromname
  * @param integer $html
  * @param string $altbody
  * @param string $ccaddress
  * @param string $ccname
  * @param string $bcc
  * @throws Exception
  */
 public static function send($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname, $html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '')
 {
     $SMTPMODE = OC_Config::getValue('mail_smtpmode', 'sendmail');
     $SMTPHOST = OC_Config::getValue('mail_smtphost', '127.0.0.1');
     $SMTPPORT = OC_Config::getValue('mail_smtpport', 25);
     $SMTPAUTH = OC_Config::getValue('mail_smtpauth', false);
     $SMTPAUTHTYPE = OC_Config::getValue('mail_smtpauthtype', 'LOGIN');
     $SMTPUSERNAME = OC_Config::getValue('mail_smtpname', '');
     $SMTPPASSWORD = OC_Config::getValue('mail_smtppassword', '');
     $SMTPDEBUG = OC_Config::getValue('mail_smtpdebug', false);
     $SMTPTIMEOUT = OC_Config::getValue('mail_smtptimeout', 10);
     $SMTPSECURE = OC_Config::getValue('mail_smtpsecure', '');
     $mailo = new PHPMailer(true);
     if ($SMTPMODE == 'sendmail') {
         $mailo->IsSendmail();
     } elseif ($SMTPMODE == 'smtp') {
         $mailo->IsSMTP();
     } elseif ($SMTPMODE == 'qmail') {
         $mailo->IsQmail();
     } else {
         $mailo->IsMail();
     }
     $mailo->Host = $SMTPHOST;
     $mailo->Port = $SMTPPORT;
     $mailo->SMTPAuth = $SMTPAUTH;
     $mailo->SMTPDebug = $SMTPDEBUG;
     $mailo->SMTPSecure = $SMTPSECURE;
     $mailo->AuthType = $SMTPAUTHTYPE;
     $mailo->Username = $SMTPUSERNAME;
     $mailo->Password = $SMTPPASSWORD;
     $mailo->Timeout = $SMTPTIMEOUT;
     $mailo->From = $fromaddress;
     $mailo->FromName = $fromname;
     $mailo->Sender = $fromaddress;
     $mailo->XMailer = ' ';
     try {
         $toaddress = self::buildAsciiEmail($toaddress);
         $mailo->AddAddress($toaddress, $toname);
         if ($ccaddress != '') {
             $mailo->AddCC($ccaddress, $ccname);
         }
         if ($bcc != '') {
             $mailo->AddBCC($bcc);
         }
         $mailo->AddReplyTo($fromaddress, $fromname);
         $mailo->WordWrap = 78;
         $mailo->IsHTML($html == 1);
         $mailo->Subject = $subject;
         if ($altbody == '') {
             $mailo->Body = $mailtext . OC_MAIL::getfooter();
             $mailo->AltBody = '';
         } else {
             $mailo->Body = $mailtext;
             $mailo->AltBody = $altbody;
         }
         $mailo->CharSet = 'UTF-8';
         $mailo->Send();
         unset($mailo);
         OC_Log::write('mail', 'Mail from ' . $fromname . ' (' . $fromaddress . ')' . ' to: ' . $toname . '(' . $toaddress . ')' . ' subject: ' . $subject, OC_Log::DEBUG);
     } catch (Exception $exception) {
         OC_Log::write('mail', $exception->getMessage(), OC_Log::ERROR);
         throw $exception;
     }
 }
Example #24
0
/**
 * Function to mail the content
 * @param string $content
 * @param string $subject
 * @param string $email           (from email)
 * @param string $realname        (from name)
 * @param string/array $recipient (to)
 * @return void
 */
function mail_it($content, $subject, $email, $realname, $recipient, $inbound = true)
{
    global $attachment_chunk, $attachment_name, $attachment_type, $attachment_temp;
    global $local_chunk, $local_name, $local_type, $local_temp;
    global $bcc, $cc;
    global $PHPMailerLocation, $PHPMailerLiteLocation;
    global $fixedFromEmail, $fixedFromName, $text_only, $htmlCharset;
    global $addToCSV;
    $valSent = false;
    if ($realname) {
        $sendTo = $realname . "<" . $email . ">";
    } else {
        $sendTo = $email;
    }
    $ob = "----=_OuterBoundary_000";
    $ib = "----=_InnerBoundery_001";
    $mail_headers = "MIME-Version: 1.0\r\n";
    if ($fixedFromEmail != '') {
        $mail_headers .= "From: " . $fixedFromEmail . "\n";
    } else {
        $mail_headers .= "From: " . $sendTo . "\n";
    }
    $mail_headers .= "To: " . $recipient . "\n";
    $mail_headers .= "Reply-To: " . $sendTo . "\n";
    if ($cc) {
        $mail_headers .= "Cc: " . $cc . "\n";
    }
    if ($bcc) {
        $mail_headers .= "Bcc: " . $bcc . "\n";
    }
    $mail_headers .= "X-Priority: 1\n";
    $mail_headers .= "X-Mailer: PHPMailer-FE v" . VERSION . " (software by worxware.com)\n";
    $mail_headers .= "Content-Type: multipart/mixed;\n\tboundary=\"" . $ob . "\"\n";
    $mail_message = "This is a multi-part message in MIME format.\n";
    $mail_message .= "\n--" . $ob . "\n";
    $mail_message .= "Content-Type: multipart/alternative;\n\tboundary=\"" . $ib . "\"\n\n";
    $mail_message .= "\n--" . $ib . "\n";
    $mail_message .= "Content-Type: text/plain;\n\tcharset=\"" . $htmlCharset . "\"\n";
    $mail_message .= "Content-Transfer-Encoding: quoted-printable\n\n";
    $mail_message .= $content["text"] . "\n\n";
    $mail_message .= "\n--" . $ib . "--\n";
    if ($attachment_name && $inbound) {
        reset($attachment_name);
        reset($attachment_temp);
        //loop through the arrays to get the attached file names and attach each one.
        while ((list($key1, $val1) = each($attachment_name)) && (list($key2, $val2) = each($attachment_temp)) && (list($key3, $val3) = each($attachment_type)) && (list($key4, $val4) = each($attachment_chunk))) {
            $mail_message .= "\n--" . $ob . "\n";
            $mail_message .= "Content-Type: {$val3};\n\tname=\"" . $val1 . "\"\n";
            $mail_message .= "Content-Transfer-Encoding: base64\n";
            $mail_message .= "Content-Disposition: attachment;\n\tfilename=\"" . $val1 . "\"\n\n";
            $mail_message .= $val4;
            $mail_message .= "\n\n";
        }
    } else {
        if ($local_name && $inbound === false) {
            $mail_message .= "\n--" . $ob . "\n";
            $mail_message .= "Content-Type: {$local_type};\n\tname=\"" . $local_name . "\"\n";
            $mail_message .= "Content-Transfer-Encoding: base64\n";
            $mail_message .= "Content-Disposition: attachment;\n\tfilename=\"" . $local_name . "\"\n\n";
            $mail_message .= $local_chunk;
            $mail_message .= "\n\n";
        }
    }
    $mail_message .= "\n--" . $ob . "--\n";
    if ((class_exists('PHPMailerLite') || class_exists('PHPMailer') || file_exists($PHPMailerLocation) || file_exists($PHPMailerLiteLocation)) && $_POST['text_only'] !== true) {
        if (!class_exists('PHPMailerLite') && file_exists($PHPMailerLiteLocation)) {
            require_once $PHPMailerLiteLocation;
            $mail = new PHPMailerLite();
        } elseif (!class_exists('PHPMailer') && file_exists($PHPMailerLocation)) {
            require_once $PHPMailerLocation;
            $mail = new PHPMailer();
        }
        if (isset($_POST['Mailer']) && strtolower(trim($_POST['Mailer'])) == "smtp") {
            $mail->IsSMTP();
            if (isset($_POST['Host']) && trim($_POST['Host']) != "") {
                $mail->Host = trim($_POST['Host']);
            }
            if (isset($_POST['Port']) && trim($_POST['Port']) != "") {
                $mail->Port = trim($_POST['Port']);
            }
            if (isset($_POST['SMTPAuth']) && ($_POST['SMTPAuth'] === true || $_POST['SMTPAuth'] === false)) {
                $mail->SMTPAuth = $_POST['SMTPAuth'];
            }
            if (isset($_POST['Username']) && trim($_POST['Username']) != "") {
                $mail->Username = trim($_POST['Username']);
            }
            if (isset($_POST['Username']) && trim($_POST['Username']) != "") {
                $mail->Password = trim($_POST['Password']);
            }
            if (isset($_POST['Timeout']) && trim($_POST['Timeout']) != "") {
                $mail->Timeout = trim($_POST['Timeout']);
            }
        } elseif (isset($_POST['Mailer']) && strtolower(trim($_POST['Mailer'])) == "sendmail") {
            $mail->IsSendmail();
        } elseif (isset($_POST['Mailer']) && strtolower(trim($_POST['Mailer'])) == "qmail") {
            $mail->IsQmail();
        }
        if (isset($_POST['fixedFromEmail'])) {
            if (isset($_POST['fixedFromName']) && trim($_POST['fixedFromName']) == '') {
                $_POST['fixedFromName'] = $_POST['fixedFromEmail'];
            }
            if (stristr($mail->Version, '5.1')) {
                $mail->SetFrom($_POST['fixedFromEmail'], $_POST['fixedFromName']);
            } elseif (stristr($mail->Version, '5')) {
                $mail->SetFrom($_POST['fixedFromEmail'], $_POST['fixedFromName']);
                $mail->AddReplyTo($_POST['fixedFromEmail'], $_POST['fixedFromName']);
            } else {
                $mail->SetFrom($_POST['fixedFromEmail'], $_POST['fixedFromName']);
            }
        } else {
            if (!isset($realname) && trim($realname) == '') {
                $realname = $email;
            }
            if (stristr($mail->Version, '5.1')) {
                $mail->SetFrom($email, $realname);
            } elseif ($mail->Version >= 5) {
                $mail->SetFrom($email, $realname);
                $mail->AddReplyTo($email, $realname);
            } else {
                $mail->From = $email;
                $mail->FromName = $realname;
            }
        }
        $mail->Subject = $subject;
        $mail->AddAddress($recipient);
        if ($bcc) {
            if (strpos($bcc, ",") || strpos($bcc, ";")) {
                $bcc_in = explode(',', $bcc);
                foreach ($bcc_in as $key => $value) {
                    $mail->AddBcc($value);
                }
            } else {
                $mail->AddBcc($bcc);
            }
        }
        if ($cc) {
            if (strpos($cc, ",") || strpos($cc, ";")) {
                $cc_in = explode(',', $cc);
                foreach ($cc_in as $key => $value) {
                    $mail->AddCc($value);
                }
            } else {
                $mail->AddCc($cc);
            }
        }
        $mail->MsgHTML($content["html"]);
        $mail->AltBody = _html2txt($content['html']);
        if ($attachment_name && $inbound) {
            //Add attachment function is in phpmailer
            //reset the arrays to the top
            reset($attachment_name);
            reset($attachment_temp);
            //loop through the arrays to get the attached file names and attach each one.
            while ((list($key1, $val1) = each($attachment_name)) && (list($key2, $val2) = each($attachment_temp))) {
                $atchmnt = file_get_contents($val2);
                $mail->AddStringAttachment($atchmnt, $val1);
            }
        } else {
            if ($local_name && $inbound === false) {
                $mail->AddAttachment($local_temp, $local_name);
            }
        }
        if ($mail->Send()) {
            echo '<script type="text/javascript">document.getElementById("feprocessing").src="_src/complete.gif";</script>';
            $valSent = true;
        }
    } else {
        if (@mail($recipient, $subject, $mail_message, $mail_headers)) {
            echo '<script type="text/javascript">document.getElementById("feprocessing").src="_src/complete.gif";</script>';
            $valSent = true;
        }
    }
    if ($addToCSV) {
        $writeVal = _writeLine($subject, $content['csv']);
    }
    if ($valSent) {
        return true;
    }
}
/**
* This function mails a text $body to the recipient $to.
* You can use more than one recipient when using a semikolon separated string with recipients.
*
* @param string $body Body text of the email in plain text or HTML
* @param mixed $subject Email subject
* @param mixed $to Array with several email addresses or single string with one email address
* @param mixed $from
* @param mixed $sitename
* @param mixed $ishtml
* @param mixed $bouncemail
* @param mixed $attachment
* @return bool If successful returns true
*/
function SendEmailMessage($body, $subject, $to, $from, $sitename, $ishtml = false, $bouncemail = null, $attachments = null, $customheaders = "")
{
    global $maildebug, $maildebugbody;
    $emailmethod = Yii::app()->getConfig('emailmethod');
    $emailsmtphost = Yii::app()->getConfig("emailsmtphost");
    $emailsmtpuser = Yii::app()->getConfig("emailsmtpuser");
    $emailsmtppassword = Yii::app()->getConfig("emailsmtppassword");
    $emailsmtpdebug = Yii::app()->getConfig("emailsmtpdebug");
    $emailsmtpssl = Yii::app()->getConfig("emailsmtpssl");
    $defaultlang = Yii::app()->getConfig("defaultlang");
    $emailcharset = Yii::app()->getConfig("emailcharset");
    if ($emailcharset != 'utf-8') {
        $body = mb_convert_encoding($body, $emailcharset, 'utf-8');
        $subject = mb_convert_encoding($subject, $emailcharset, 'utf-8');
        $sitename = mb_convert_encoding($sitename, $emailcharset, 'utf-8');
    }
    if (!is_array($to)) {
        $to = array($to);
    }
    if (!is_array($customheaders) && $customheaders == '') {
        $customheaders = array();
    }
    if (Yii::app()->getConfig('demoMode')) {
        $maildebug = gT('Email was not sent because demo-mode is activated.');
        $maildebugbody = '';
        return false;
    }
    if (is_null($bouncemail)) {
        $sender = $from;
    } else {
        $sender = $bouncemail;
    }
    require_once APPPATH . '/third_party/phpmailer/class.phpmailer.php';
    $mail = new PHPMailer();
    if (!$mail->SetLanguage($defaultlang, APPPATH . '/third_party/phpmailer/language/')) {
        $mail->SetLanguage('en', APPPATH . '/third_party/phpmailer/language/');
    }
    $mail->CharSet = $emailcharset;
    if (isset($emailsmtpssl) && trim($emailsmtpssl) !== '' && $emailsmtpssl !== 0) {
        if ($emailsmtpssl === 1) {
            $mail->SMTPSecure = "ssl";
        } else {
            $mail->SMTPSecure = $emailsmtpssl;
        }
    }
    $fromname = '';
    $fromemail = $from;
    if (strpos($from, '<')) {
        $fromemail = substr($from, strpos($from, '<') + 1, strpos($from, '>') - 1 - strpos($from, '<'));
        $fromname = trim(substr($from, 0, strpos($from, '<') - 1));
    }
    $sendername = '';
    $senderemail = $sender;
    if (strpos($sender, '<')) {
        $senderemail = substr($sender, strpos($sender, '<') + 1, strpos($sender, '>') - 1 - strpos($sender, '<'));
        $sendername = trim(substr($sender, 0, strpos($sender, '<') - 1));
    }
    switch ($emailmethod) {
        case "qmail":
            $mail->IsQmail();
            break;
        case "smtp":
            $mail->IsSMTP();
            if ($emailsmtpdebug > 0) {
                $mail->SMTPDebug = $emailsmtpdebug;
            }
            if (strpos($emailsmtphost, ':') > 0) {
                $mail->Host = substr($emailsmtphost, 0, strpos($emailsmtphost, ':'));
                $mail->Port = substr($emailsmtphost, strpos($emailsmtphost, ':') + 1);
            } else {
                $mail->Host = $emailsmtphost;
            }
            $mail->Username = $emailsmtpuser;
            $mail->Password = $emailsmtppassword;
            if (trim($emailsmtpuser) != "") {
                $mail->SMTPAuth = true;
            }
            break;
        case "sendmail":
            $mail->IsSendmail();
            break;
        default:
            //Set to the default value to rule out incorrect settings.
            $emailmethod = "mail";
            $mail->IsMail();
    }
    $mail->SetFrom($fromemail, $fromname);
    $mail->Sender = $senderemail;
    // Sets Return-Path for error notifications
    foreach ($to as $singletoemail) {
        if (strpos($singletoemail, '<')) {
            $toemail = substr($singletoemail, strpos($singletoemail, '<') + 1, strpos($singletoemail, '>') - 1 - strpos($singletoemail, '<'));
            $toname = trim(substr($singletoemail, 0, strpos($singletoemail, '<') - 1));
            $mail->AddAddress($toemail, $toname);
        } else {
            $mail->AddAddress($singletoemail);
        }
    }
    if (is_array($customheaders)) {
        foreach ($customheaders as $key => $val) {
            $mail->AddCustomHeader($val);
        }
    }
    $mail->AddCustomHeader("X-Surveymailer: {$sitename} Emailer (LimeSurvey.sourceforge.net)");
    if (get_magic_quotes_gpc() != "0") {
        $body = stripcslashes($body);
    }
    if ($ishtml) {
        $mail->IsHTML(true);
        if (strpos($body, "<html>") === false) {
            $body = "<html>" . $body . "</html>";
        }
        $mail->msgHTML($body, App()->getConfig("publicdir"));
        // This allow embedded image if we remove the servername from image
    } else {
        $mail->IsHTML(false);
        $mail->Body = $body;
    }
    // Add attachments if they are there.
    if (is_array($attachments)) {
        foreach ($attachments as $attachment) {
            // Attachment is either an array with filename and attachment name.
            if (is_array($attachment)) {
                $mail->AddAttachment($attachment[0], $attachment[1]);
            } else {
                // Or a string with the filename.
                $mail->AddAttachment($attachment);
            }
        }
    }
    $mail->Subject = $subject;
    if ($emailsmtpdebug > 0) {
        ob_start();
    }
    $sent = $mail->Send();
    $maildebug = $mail->ErrorInfo;
    if ($emailsmtpdebug > 0) {
        $maildebug .= '<li>' . gT('SMTP debug output:') . '</li><pre>' . strip_tags(ob_get_contents()) . '</pre>';
        ob_end_clean();
    }
    $maildebugbody = $mail->Body;
    //if(!$sent) var_dump($maildebug);
    return $sent;
}
Example #26
0
 /**
  * Reset a new password to an user and send by email
  * @param string $to
  * @param string $from
  * @param string $replyTo
  * @param string $subject
  * @param string $body
  * @return array
  */
 public static function sendMail($to, $from, $replyTo, $subject, $body)
 {
     include_once 'lib/phpmailer/class.phpmailer.php';
     $mailer = new \PHPMailer();
     if (\app::$config['mail']['type'] === 'smtp') {
         $mailer->IsSMTP();
         $mailer->Host = \app::$config['mail']['server'];
         $mailer->Port = \app::$config['mail']['port'];
     } elseif (\app::$config['mail']['type'] === 'sendmail') {
         $mailer->IsSendmail();
     } elseif (\app::$config['mail']['type'] === 'qmail') {
         $mailer->IsQmail();
     }
     if (strstr($to, ',') !== FALSE) {
         $multi = explode(',', $to);
         foreach ($multi as $addr) {
             $mailer->AddAddress(trim($addr));
         }
     } else {
         $mailer->AddAddress($to);
     }
     $mailer->SetFrom($from);
     $mailer->AddReplyTo($replyTo);
     $mailer->Subject = $subject;
     $mailer->AltBody = 'To view the message, please use an HTML compatible email viewer!';
     $mailer->MsgHTML($body);
     return $mailer->Send();
 }