smtpClose() public method

Close the active SMTP session if one exists.
public smtpClose ( ) : void
return void
Example #1
1
 public function smtp($to, $subject, $body, $option = null)
 {
     if (is_array($option)) {
         if (array_key_exists('name', $option)) {
             $this->name = $option['name'];
         }
         if (array_key_exists('debug', $option)) {
             $this->debug = $option['debug'];
         }
     }
     $mail = new PHPMailer(true);
     try {
         $mail->IsSMTP();
         // telling the class to use SMTP
         $mail->CharSet = 'UTF-8';
         $mail->XMailer = ' ';
         $mail->IsHTML(true);
         //$mail->SMTPSecure = 'tls';
         $mail->SMTPDebug = $this->debug;
         // enables SMTP debug information (for testing)
         // 1 = errors and messages
         // 2 = messages only
         $mail->Host = $this->host;
         // sets the SMTP server
         $mail->Port = 25;
         // set the SMTP port for the GMAIL server
         $mail->SMTPAuth = false;
         // enable SMTP authentication
         $mail->Username = $this->username;
         // SMTP account username
         $mail->Password = $this->password;
         // SMTP account password
         $mail->SetFrom($this->from, 'Webmaster');
         $mail->AddReplyTo($this->replyto, 'Webmaster');
         $mail->Subject = $subject;
         //$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
         //$body             = eregi_replace("[\]",'',$body);
         $mail->MsgHTML($body);
         $mail->ClearAddresses();
         $mail->AddAddress($to, $this->name);
         //$mail->AddAttachment("images/phpmailer.gif");      // attachment
         //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
         if (!$mail->Send()) {
             echo "Mailer Error: " . $mail->ErrorInfo;
         }
     } catch (phpmailerException $e) {
         echo $e->errorMessage();
         //Pretty error messages from PHPMailer
     } catch (Exception $e) {
         echo $e->getMessage();
         //Boring error messages from anything else!
     } finally {
         $mail->smtpClose();
     }
 }
Example #2
0
 /**
  * Test SMTP host connections.
  * This test can take a long time, so run it last.
  */
 public function testSmtpConnect()
 {
     $this->assertTrue($this->Mail->smtpConnect(), 'SMTP single connect failed');
     $this->Mail->smtpClose();
     $this->Mail->Host = 'ssl://localhost:12345;tls://localhost:587;10.10.10.10:54321;localhost:12345;10.10.10.10';
     $this->assertFalse($this->Mail->smtpConnect(), 'SMTP bad multi-connect succeeded');
     $this->Mail->smtpClose();
     $this->Mail->Host = 'localhost:12345;10.10.10.10:54321;' . $_REQUEST['mail_host'];
     $this->assertTrue($this->Mail->smtpConnect(), 'SMTP multi-connect failed');
     $this->Mail->smtpClose();
     $this->Mail->Host = ' localhost:12345 ; ' . $_REQUEST['mail_host'] . ' ';
     $this->assertTrue($this->Mail->smtpConnect(), 'SMTP hosts with stray spaces failed');
     $this->Mail->smtpClose();
     $this->Mail->Host = $_REQUEST['mail_host'];
     //Need to pick a harmless option so as not cause problems of its own! socket:bind doesn't work with Travis-CI
     $this->assertTrue($this->Mail->smtpConnect(['ssl' => ['verify_depth' => 10]]), 'SMTP connect with options failed');
 }
Example #3
0
             $mail->Workstation = $phpwcms['SMTP_WORKSTATION'];
         }
     }
 }
 $mail->From = $newsletter['newsletter_vars']['from_email'];
 $mail->FromName = $newsletter['newsletter_vars']['from_name'];
 $mail->Sender = $newsletter['newsletter_vars']['replyto'];
 $mail->Subject = $newsletter['newsletter_subject'];
 if (!$mail->setLanguage($phpwcms['default_lang'], PHPWCMS_ROOT . '/include/inc_ext/phpmailer/language/')) {
     $mail->setLanguage('en', PHPWCMS_ROOT . '/include/inc_ext/phpmailer/language/');
 }
 $mail->SMTPKeepAlive = true;
 $x = 0;
 foreach ($recipient as $value) {
     if ($x == 20) {
         $mail->smtpClose();
         // Manually close the SMTP connection
         $mail->SMTPKeepAlive = true;
     }
     $mail->addAddress($value['address_email'], $value['address_name']);
     if ($newsletter['newsletter_vars']['html'] && $newsletter['newsletter_vars']['text']) {
         //send both TEXT and HTML part
         $mail->Body = build_email_text($newsletter['newsletter_vars']['html'], $value);
         $mail->AltBody = build_email_text($newsletter['newsletter_vars']['text'], $value);
         $mail->isHTML(1);
     }
     if ($newsletter['newsletter_vars']['html'] && !$newsletter['newsletter_vars']['text']) {
         //send HTML part
         $mail->Body = build_email_text($newsletter['newsletter_vars']['html'], $value);
         $mail->isHTML(1);
     }
Example #4
0
 /**
  * A mail testing utility.
  *
  * @since 141111 First documented version.
  *
  * @note  This method always (ALWAYS) sends email in HTML format;
  *    w/ a plain text alternative — generated automatically.
  *
  * @param string|array $to          Email address(es).
  * @param string       $subject     Email subject line.
  * @param string       $message     Message contents.
  * @param string|array $headers     Optional. Additional headers.
  * @param string|array $attachments Optional. Files to attach.
  *
  * @return \stdClass With the following properties:
  *
  *    • `to` = addresses the test was sent to; as an array.
  *    • `via` = the transport layer used in the test; as a string.
  *    • `sent` = `TRUE` if the email was sent successfully; as a boolean.
  *    • `debug_output_markup` = HTML markup w/ any debugging output; as a string.
  *    • `results_markup` = Markup with all of the above in test response format; as a string.
  */
 public function test($to, $subject, $message, $headers = [], $attachments = [])
 {
     if ($this->isSmtpEnabled()) {
         // Can use SMTP; i.e. enabled?
         return $this->smtpTest($to, $subject, $message, $headers, $attachments);
     }
     $to = array_map('strval', (array) $to);
     // Force array.
     $via = 'wp_mail';
     // Via `wp_mail` in this case.
     $sent = false;
     // Initialize as `FALSE`.
     global $phpmailer;
     // WP global var.
     if (!$phpmailer instanceof \PHPMailer) {
         require_once ABSPATH . WPINC . '/class-phpmailer.php';
         require_once ABSPATH . WPINC . '/class-smtp.php';
         $phpmailer = new \PHPMailer(true);
     }
     ob_start();
     $phpmailer->SMTPDebug = 2;
     $phpmailer->Debugoutput = 'html';
     // Note: `wp_mail()` might not actually use \PHPMailer.
     // If that's the case, then debug output below will likely be empty.
     // It's also possible that \PHPMailer is not using SMTP. That's OK too.
     if (!is_array($headers)) {
         // Force array.
         $headers = explode("\r\n", (string) $headers);
     }
     if ($_content_type_keys = $this->headerExists('Content-Type', $headers)) {
         foreach ($_content_type_keys as $_content_type_key) {
             unset($headers[$_content_type_key]);
         }
     }
     unset($_content_type_keys, $_content_type_key);
     // Housekeeping.
     $headers[] = 'Content-Type: text/html; charset=UTF-8';
     // Force this, always.
     if ($this->plugin->options['from_email'] && !$this->headerExists('From', $headers)) {
         $headers[] = 'From: "' . $this->plugin->utils_string->escDq($this->plugin->options['from_name']) . '"' . ' <' . $this->plugin->options['from_email'] . '>';
     }
     if ($this->plugin->options['reply_to_email'] && !$this->headerExists('Reply-To', $headers)) {
         $headers[] = 'Reply-To: ' . $this->plugin->options['reply_to_email'];
     }
     $sent = wp_mail($to, $subject, $message, $headers, $attachments);
     if ($phpmailer instanceof \PHPMailer && $phpmailer->Mailer === 'smtp') {
         $phpmailer->smtpClose();
     }
     unset($phpmailer);
     // Unset so WordPress will recreate if it needs it again in this process.
     $debug_output_markup = $this->plugin->utils_string->trimHtml(ob_get_clean());
     $results_markup = $this->testResultsMarkup($to, $via, $sent, $debug_output_markup);
     return (object) compact('to', 'via', 'sent', 'debug_output_markup', 'results_markup');
 }
Example #5
0
 public function check()
 {
     $checkStart = (int) $this->_config->get("general", "check_start", 7);
     $checkEnd = (int) $this->_config->get("general", "check_end", 24);
     if ($checkStart > 23) {
         $checkStart = 0;
     }
     if ($checkEnd < 1) {
         $checkEnd = 24;
     }
     $hour = (int) date("G");
     if ($hour < $checkStart || $hour >= $checkEnd) {
         $this->_logger->info("Hors de la plage horaire. Contrôle annulé.");
         return;
     }
     $this->_logger->info("Contrôle des alertes.");
     $this->_checkConnection();
     $users = $this->_userStorage->fetchAll();
     // génération d'URL court pour les SMS
     $curlTinyurl = curl_init();
     curl_setopt($curlTinyurl, CURLOPT_RETURNTRANSFER, 1);
     $storageType = $this->_config->get("storage", "type", "files");
     foreach ($users as $user) {
         if ($storageType == "db") {
             $storage = new \App\Storage\Db\Alert($this->_userStorage->getDbConnection(), $user);
             $this->_logger->info("User: "******"/var/configs/" . $user->getUsername() . ".csv";
             if (!is_file($file)) {
                 continue;
             }
             $storage = new \App\Storage\File\Alert($file);
             $this->_logger->debug("Fichier config: " . $file);
         }
         // configuration des notifications.
         $notifications = array();
         $notifications_params = $user->getOption("notification");
         if ($notifications_params && is_array($notifications_params)) {
             foreach ($notifications_params as $notification_name => $options) {
                 if (!is_array($options)) {
                     continue;
                 }
                 try {
                     $notifications[$notification_name] = \Message\AdapterFactory::factory($notification_name, $options);
                     $this->_logger->debug("notification " . get_class($notifications[$notification_name]) . " activée");
                 } catch (\Exception $e) {
                     $this->_logger->warn("notification " . $notification_name . " invalide");
                 }
             }
         }
         $alerts = $storage->fetchAll();
         $this->_logger->info(count($alerts) . " alerte" . (count($alerts) > 1 ? "s" : "") . " trouvée" . (count($alerts) > 1 ? "s" : ""));
         if (count($alerts) == 0) {
             continue;
         }
         $unique_ads = $user->getOption("unique_ads");
         foreach ($alerts as $i => $alert) {
             $currentTime = time();
             if (!isset($alert->time_updated)) {
                 $alert->time_updated = 0;
             }
             if ((int) $alert->time_updated + (int) $alert->interval * 60 > $currentTime || $alert->suspend) {
                 continue;
             }
             $this->_logger->info("Contrôle de l'alerte " . $alert->url);
             try {
                 $parser = \AdService\ParserFactory::factory($alert->url);
             } catch (\AdService\Exception $e) {
                 $this->_logger->info("\t" . $e->getMessage());
                 continue;
             }
             $this->_logger->debug("Dernière mise à jour : " . (!empty($alert->time_updated) ? date("d/m/Y H:i", (int) $alert->time_updated) : "inconnue"));
             $this->_logger->debug("Dernière annonce : " . (!empty($alert->time_last_ad) ? date("d/m/Y H:i", (int) $alert->time_last_ad) : "inconnue"));
             $alert->time_updated = $currentTime;
             if (!($content = $this->_httpClient->request($alert->url))) {
                 $this->_logger->error("Curl Error : " . $this->_httpClient->getError());
                 continue;
             }
             $cities = array();
             if ($alert->cities) {
                 $cities = array_map("trim", explode("\n", mb_strtolower($alert->cities)));
             }
             $filter = new \AdService\Filter(array("price_min" => $alert->price_min, "price_max" => $alert->price_max, "cities" => $cities, "price_strict" => (bool) $alert->price_strict, "categories" => $alert->getCategories(), "min_id" => $unique_ads ? $alert->last_id : 0));
             $ads = $parser->process($content, $filter, parse_url($alert->url, PHP_URL_SCHEME));
             $countAds = count($ads);
             if ($countAds == 0) {
                 $storage->save($alert);
                 continue;
             }
             $siteConfig = \AdService\SiteConfigFactory::factory($alert->url);
             $newAds = array();
             $time_last_ad = (int) $alert->time_last_ad;
             foreach ($ads as $ad) {
                 if ($time_last_ad < $ad->getDate()) {
                     $newAds[$ad->getId()] = (require DOCUMENT_ROOT . "/app/mail/views/mail-ad.phtml");
                     if ($alert->time_last_ad < $ad->getDate()) {
                         $alert->time_last_ad = $ad->getDate();
                     }
                     if ($unique_ads && $ad->getId() > $alert->last_id) {
                         $alert->last_id = $ad->getId();
                     }
                 }
             }
             if (!$newAds) {
                 $storage->save($alert);
                 continue;
             }
             $countAds = count($newAds);
             $this->_logger->info($countAds . " annonce" . ($countAds > 1 ? "s" : "") . " trouvée" . ($countAds > 1 ? "s" : ""));
             $this->_mailer->clearAddresses();
             $error = false;
             if ($alert->send_mail) {
                 try {
                     $emails = explode(",", $alert->email);
                     foreach ($emails as $email) {
                         $this->_mailer->addAddress(trim($email));
                     }
                 } catch (phpmailerException $e) {
                     $this->_logger->warn($e->getMessage());
                     $error = true;
                 }
                 if (!$error) {
                     if ($alert->group_ads) {
                         $newAdsCount = count($newAds);
                         $subject = "Alert " . $siteConfig->getOption("site_name") . " : " . $alert->title;
                         $message = '<h2>' . $newAdsCount . ' nouvelle' . ($newAdsCount > 1 ? 's' : '') . ' annonce' . ($newAdsCount > 1 ? 's' : '') . ' - ' . date("d/m/Y H:i", $currentTime) . '</h2>
                         <p>Lien de recherche: <a href="' . htmlspecialchars($alert->url, null, "UTF-8") . '">' . htmlspecialchars($alert->url, null, "UTF-8") . '</a></p>
                         <hr /><br />' . implode("<br /><hr /><br />", $newAds) . '<hr /><br />';
                         $this->_mailer->Subject = $subject;
                         $this->_mailer->Body = $message;
                         try {
                             $this->_mailer->send();
                         } catch (phpmailerException $e) {
                             $this->_logger->warn($e->getMessage());
                         }
                     } else {
                         $newAds = array_reverse($newAds, true);
                         foreach ($newAds as $id => $ad) {
                             $subject = ($alert->title ? $alert->title . " : " : "") . $ads[$id]->getTitle();
                             $message = '<h2>Nouvelle annonce - ' . date("d/m/Y H:i", $currentTime) . '</h2>
                             <p>Lien de recherche: <a href="' . htmlspecialchars($alert->url, null, "UTF-8") . '">' . htmlspecialchars($alert->url, null, "UTF-8") . '</a></p>
                             <hr /><br />' . $ad . '<hr /><br />';
                             $this->_mailer->Subject = $subject;
                             $this->_mailer->Body = $message;
                             try {
                                 $this->_mailer->send();
                             } catch (phpmailerException $e) {
                                 $this->_logger->warn($e->getMessage());
                             }
                         }
                     }
                 }
             }
             if ($notifications && ($alert->send_sms_free_mobile || $alert->send_sms_ovh || $alert->send_pushbullet || $alert->send_notifymyandroid || $alert->send_pushover)) {
                 if ($countAds < 5) {
                     // limite à 5 SMS
                     foreach ($newAds as $id => $ad) {
                         $ad = $ads[$id];
                         // récupère l'objet.
                         $url = $ad->getLink();
                         if (false !== strpos($url, "leboncoin")) {
                             $url = "http://mobile.leboncoin.fr/vi/" . $ad->getId() . ".htm";
                         }
                         curl_setopt($curlTinyurl, CURLOPT_URL, "http://tinyurl.com/api-create.php?url=" . $url);
                         if ($url = curl_exec($curlTinyurl)) {
                             $msg = "Nouvelle annonce " . ($alert->title ? $alert->title . " : " : "") . $ad->getTitle();
                             $others = array();
                             if ($ad->getPrice()) {
                                 $others[] = number_format($ad->getPrice(), 0, ',', ' ') . $ad->getCurrency();
                             }
                             if ($ad->getCity()) {
                                 $others[] = $ad->getCity();
                             } elseif ($ad->getCountry()) {
                                 $others[] = $ad->getCountry();
                             }
                             if ($others) {
                                 $msg .= " (" . implode(", ", $others) . ")";
                             }
                             $params = array("title" => "Alerte " . $siteConfig->getOption("site_name"), "description" => "Nouvelle annonce" . ($alert->title ? " pour : " . $alert->title : ""), "url" => $url);
                             foreach ($notifications as $key => $notifier) {
                                 switch ($key) {
                                     case "freeMobile":
                                         $key_test = "send_sms_free_mobile";
                                         break;
                                     case "ovh":
                                         $key_test = "send_sms_ovh";
                                         break;
                                     default:
                                         $key_test = "send_" . $key;
                                 }
                                 if (isset($alert->{$key_test}) && $alert->{$key_test}) {
                                     try {
                                         $notifier->send($msg, $params);
                                     } catch (Exception $e) {
                                         $this->_logger->warn("Erreur sur envoi via " . get_class($notifier) . ": (" . $e->getCode() . ") " . $e->getMessage());
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     // envoi un msg global
                     curl_setopt($curlTinyurl, CURLOPT_URL, "http://tinyurl.com/api-create.php?url=" . $alert->url);
                     if ($url = curl_exec($curlTinyurl)) {
                         $msg = "Il y a " . $countAds . " nouvelles annonces pour votre alerte '" . ($alert->title ? $alert->title : "sans nom") . "'";
                         $params = array("title" => "Alerte " . $siteConfig->getOption("site_name"), "description" => "Nouvelle" . ($countAds > 1 ? "s" : "") . " annonce" . ($countAds > 1 ? "s" : "") . ($alert->title ? " pour : " . $alert->title : ""), "url" => $url);
                         foreach ($notifications as $key => $notifier) {
                             switch ($key) {
                                 case "freeMobile":
                                     $key_test = "send_sms_free_mobile";
                                     break;
                                 case "ovh":
                                     $key_test = "send_sms_ovh";
                                     break;
                                 default:
                                     $key_test = "send_" . $key;
                             }
                             if (isset($alert->{$key_test}) && $alert->{$key_test}) {
                                 try {
                                     $notifier->send($msg, $params);
                                 } catch (Exception $e) {
                                     $this->_logger->warn("Erreur sur envoi via " . get_class($notifier) . ": (" . $e->getCode() . ") " . $e->getMessage());
                                 }
                             }
                         }
                     }
                 }
             }
             $storage->save($alert);
         }
     }
     curl_close($curlTinyurl);
     $this->_mailer->smtpClose();
 }
Example #6
0
 /**
  *
  */
 public function close()
 {
     $this->mail->smtpClose();
 }
 /**
  * Get smtp connection.
  *
  * @param type $request
  *
  * @return int
  */
 public function getSmtp($request)
 {
     //        dd($request);
     $sending_status = $request->input('sending_status');
     // cheking for the sending protocol
     if ($request->input('sending_protocol') == 'smtp') {
         $mail = new \PHPMailer();
         $mail->isSMTP();
         $mail->Host = $request->input('sending_host');
         // Specify main and backup SMTP servers
         //$mail->SMTPAuth = true;                                   // Enable SMTP authentication
         $mail->Username = $request->input('email_address');
         // SMTP username
         $mail->Password = $request->input('password');
         // SMTP password
         $mail->SMTPSecure = $request->input('sending_encryption');
         // Enable TLS encryption, `ssl` also accepted
         $mail->Port = $request->input('sending_port');
         // TCP port to connect to
         if (!$request->input('smtp_validate')) {
             $mail->SMTPAuth = true;
             // Enable SMTP authentication
             $mail->SMTPOptions = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true));
             if ($mail->smtpConnect($mail->SMTPOptions) == true) {
                 $mail->smtpClose();
                 $return = 1;
             } else {
                 $return = 0;
             }
         } else {
             if ($mail->smtpConnect() == true) {
                 $mail->smtpClose();
                 $return = 1;
             } else {
                 $return = 0;
             }
         }
     } elseif ($request->input('sending_protocol') == 'mail') {
         $return = 1;
     }
     return $return;
 }
function sendEmail($recipient, $aliasNames = '', $from = '佳诚装饰', $subject, $body, $attachement = null)
{
    date_default_timezone_set('PRC');
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->SMTPDebug = 2;
    $mail->Debugoutput = 'html';
    $mail->Host = "smtp.sina.com";
    $mail->Port = "465";
    $mail->SMTPSecure = "ssl";
    $mail->SMTPAuth = true;
    $mail->Username = "******";
    $mail->Password = "******";
    $mail->Priority = 1;
    $mail->Charset = 'utf-8';
    $mail->Encoding = 'base64';
    $mail->From = '*****@*****.**';
    $mail->FromName = trim($from) == '佳诚装饰' ? '' : $from;
    $mail->Timeout = 30;
    if ($recipient == null) {
        echo "recipient should not be null !<br />\n";
        die;
    }
    if (is_string($recipient) && contains($recipient, ',')) {
        $recipient = explode(',', $recipient);
    }
    if (is_string($aliasNames) && contains($aliasNames, ',')) {
        $aliasNames = explode(',', $aliasNames);
    }
    if (is_string($recipient) && contains($recipient, '@')) {
        $mail->addAddress($recipient, $aliasNames);
    }
    if (is_array($recipient)) {
        $recipient = array_merge($recipient);
        $count = count($recipient);
        $aliasNames = is_array($aliasNames) ? array_merge($aliasNames) : array();
        for ($i = 0; $i < $count; $i++) {
            $address = $recipient[$i];
            $name = isset($aliasNames[$i]) ? $aliasNames[$i] : '';
            if (is_string($address) && contains($address, '@')) {
                echo "send mail to {$address} as {$name} <br />\n";
                $mail->addAddress($address, $name);
            }
        }
    }
    // $mail->addAddress('*****@*****.**','IT_Diego');
    // $mail->addAddress('*****@*****.**','IT_Alex');
    $mail->isHTML(true);
    // Set email format to HTML
    if ($attachement != null) {
        $mail->addStringAttachment($attachement['content'], $attachement['name']);
    }
    $mail->Subject = "【佳诚装饰】 {$subject}";
    $mail->Body = $body;
    $mail->AltBody = "";
    if (!$mail->send()) {
        echo "Message could not be sent.<br />\n";
        echo "Mailer Error: " . $mail->ErrorInfo . "<br />\n";
    } else {
        echo "Message has been sent<br />\n";
    }
    $mail->smtpClose();
}
/**
 * cw_smtp_send_mail sends email via SMTP PHPmailer library
 *
 * @param
 * mail_data = array(
 * from - 'sent from' email address, optional, default value: $config['Email']['smtp_mail_from'] 
 * from_name - 'Sent from' person name, optional
 * send_to - recepient email address, required
 * send_to_name - recepient person name, optional
 * subject - email subject, required
 * body - email body, required
 * alt_body - alternative body, optional
 *
 * @return boolean
 */
function cw_smtp_send_mail($mail_data, $dbg_level = 0)
{
    global $config, $app_main_dir;
    include_once $app_main_dir . '/include/lib/PHPmailer/class.phpmailer.php';
    include_once $app_main_dir . '/include/lib/PHPmailer/class.smtp.php';
    $result = 0;
    $mail = new PHPMailer();
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = $dbg_level;
    //Ask for HTML-friendly debug output
    if ($dbg_level) {
        $mail->Debugoutput = 'html';
    }
    //Set the hostname of the mail server
    $mail->Host = $config['Email']['smtp_server'];
    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
    $mail->Port = $config['Email']['smtp_port'];
    //Set the encryption system to use - ssl (deprecated) or tls
    if ($config['Email']['smtp_use_tlc_connect'] == "Y") {
        $mail->SMTPSecure = 'tls';
    }
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //Username to use for SMTP authentication - use full email address for gmail
    $mail->Username = $config['Email']['smtp_username'];
    //Password to use for SMTP authentication
    $mail->Password = $config['Email']['smtp_password'];
    //Set who the message is to be sent from
    if ($config['Email']['smtp_mail_from_force'] != 'Y') {
        $mail_from = empty($mail_data['from']) ? $config['Email']['smtp_mail_from'] : $mail_data['from'];
    } else {
        $mail_from = $config['Email']['smtp_mail_from'];
    }
    $mail->setFrom($mail_from, $mail_data['from_name']);
    $mail->addAddress($mail_data['send_to'], $mail_data['send_to_name']);
    //Set the subject line
    $mail->Subject = $mail_data['subject'];
    //Read an HTML message body from an external file, convert referenced images to embedded,
    //convert HTML into a basic plain-text alternative body
    $mail->msgHTML($mail_data['body'], dirname(__FILE__));
    //Replace the plain text body with one created manually
    if (!empty($mail_data['alt_body'])) {
        $mail->AltBody = $mail_data['alt_body'];
    }
    //send the message, check for errors
    if (!$mail->send()) {
        cw_log_add("phpmailer", $mail->ErrorInfo);
    } else {
        $result = 1;
    }
    $mail->smtpClose();
    return $result;
}
Example #10
0
function sola_nl_ajax_send($subscribers, $camp_id)
{
    $debug_start = (double) array_sum(explode(' ', microtime()));
    global $wpdb;
    global $sola_nl_camp_tbl;
    global $sola_nl_camp_subs_tbl;
    global $sola_nl_subs_tbl;
    global $sola_global_subid;
    global $sola_global_campid;
    if ($camp_id) {
        echo get_option("sola_currently_sending");
        if (!get_option("sola_currently_sending")) {
            if (get_option("sola_currently_sending") == "yes") {
                return "We are currently sending. Dont do anything";
            } else {
                update_option("sola_currently_sending", "yes");
            }
        } else {
            add_option("sola_currently_sending", "yes");
        }
        update_option("sola_currently_sending", "yes");
        $camp = sola_nl_get_camp_details($camp_id);
        if (isset($camp->reply_to)) {
            $reply = $camp->reply_to;
        }
        if (isset($camp->reply_to_name)) {
            $reply_name = stripslashes($camp->reply_to_name);
        }
        if (isset($camp->sent_from)) {
            $sent_from = $camp->sent_from;
        }
        if (isset($camp->sent_from_name)) {
            $sent_from_name = stripslashes($camp->sent_from_name);
        }
        if (empty($reply)) {
            $reply = get_option("sola_nl_reply_to");
        }
        if (empty($reply_name)) {
            $reply_name = get_option("sola_nl_reply_to_name");
        }
        if (empty($sent_from)) {
            $sent_from = get_option("sola_nl_sent_from");
        }
        if (empty($sent_from_name)) {
            $sent_from_name = get_option("sola_nl_sent_from_name");
        }
        // get option for either SMTP or normal WP MAil
        // split below based on above
        $saved_send_method = get_option("sola_nl_send_method");
        if ($saved_send_method == "1") {
            $headers[] = 'From: ' . $sent_from_name . '<' . $sent_from . '>';
            $headers[] = 'Content-type: text/html';
            $headers[] = 'Reply-To: ' . $reply_name . '<' . $reply . '>';
        } else {
            if ($saved_send_method >= "2") {
                $file = PLUGIN_URL . '/includes/phpmailer/PHPMailerAutoload.php';
                require_once $file;
                $mail = new PHPMailer();
                $mail->IsSMTP();
                $mail->SMTPAuth = true;
                $mail->SMTPKeepAlive = true;
                $port = get_option("sola_nl_port");
                $encryption = get_option("sola_nl_encryption");
                if ($encryption) {
                    $mail->SMTPSecure = $encryption;
                }
                $host = get_option("sola_nl_host");
                $mail->Host = $host;
                $mail->Username = get_option("sola_nl_username");
                $mail->Password = get_option("sola_nl_password");
                $mail->Port = $port;
                $mail->AddReplyTo($reply, $reply_name);
                $mail->SetFrom($sent_from, $sent_from_name);
                $mail->Subject = $camp->subject;
                $mail->SMTPDebug = 0;
            }
        }
        if ($subscribers) {
            foreach ($subscribers as $subscriber) {
                set_time_limit(600);
                $sub_id = $subscriber['sub_id'];
                $sub_email = $subscriber['sub_email'];
                echo $sub_email;
                $body = sola_nl_mail_body($camp->email, $sub_id, $camp->camp_id);
                $sola_global_subid = $sub_id;
                $sola_global_campid = $camp->camp_id;
                $body = do_shortcode($body);
                $body = sola_nl_replace_links($body, $sub_id, $camp->camp_id);
                /* ------ */
                //$check = sola_mail($camp_id ,$sub_email, $camp->subject, $body);
                if ($saved_send_method == "1") {
                    if (wp_mail($sub_email, $camp->subject, $body, $headers)) {
                        $check = true;
                    } else {
                        if (!$debug) {
                            $check = array('error' => 'Error sending mail to' . $sub_email);
                        } else {
                            $check = array('error' => "Failed to send email to {$sub_email}... " . $GLOBALS['phpmailer']->ErrorInfo);
                        }
                    }
                } else {
                    if ($saved_send_method >= "2") {
                        if (is_array($sub_email)) {
                            foreach ($sub_email as $address) {
                                $mail->AddAddress($address);
                            }
                        } else {
                            $mail->AddAddress($sub_email);
                        }
                        $mail->Body = $body;
                        $mail->IsHTML(true);
                        //echo "sending to $sub_email<br />";
                        if (!$mail->Send()) {
                            $check = array('error' => 'Error sending mail to ' . $sub_email);
                        } else {
                            $check = true;
                        }
                    }
                }
                if ($check === true) {
                    sola_update_camp_limit($camp_id);
                    $wpdb->update($sola_nl_camp_subs_tbl, array('status' => 1), array('camp_id' => $camp_id, 'sub_id' => $sub_id), array('%d'), array('%d', '%d'));
                    //echo "Email sent to $sub_email successfully <br />";
                } else {
                    sola_return_error(new WP_Error('sola_error', __('Failed to send email to subscriber'), 'Could not send email to ' . $sub_email));
                    //echo "<p>Failed to send to ".$sub_email."</p>";
                }
                $mail->clearAddresses();
                $mail->clearAttachments();
                $end = (double) array_sum(explode(' ', microtime()));
                echo "<br />processing time: " . sprintf("%.4f", $end - $debug_start) . " seconds<br />";
                //$check = sola_nl_send_mail_via_cron($camp_id,$sub_id,$sub_email);
                //if ( is_wp_error($check)) sola_return_error($check);
            }
        } else {
            /* do nothing, reached limit */
        }
        if ($saved_send_method >= "2") {
            $mail->smtpClose();
        }
        $end = (double) array_sum(explode(' ', microtime()));
        echo "<br />processing time: " . sprintf("%.4f", $end - $debug_start) . " seconds<br />";
        update_option("sola_currently_sending", "no");
        sola_nl_done_sending_camp($camp_id);
    } else {
        echo "<br />nothing to send at this time<br />";
    }
}
Example #11
-2
function phorum_smtp_send_messages($data)
{
    global $PHORUM;
    $addresses = $data['addresses'];
    $subject = $data['subject'];
    $message = $data['body'];
    $num_addresses = count($addresses);
    $settings = $PHORUM['smtp_mail'];
    $settings['auth'] = empty($settings['auth']) ? false : true;
    if ($num_addresses > 0) {
        try {
            require_once "./mods/smtp_mail/phpmailer/class.phpmailer.php";
            $mail = new PHPMailer();
            $mail->PluginDir = "./mods/smtp_mail/phpmailer/";
            $mail->CharSet = $PHORUM["DATA"]["CHARSET"];
            $mail->Encoding = $PHORUM["DATA"]["MAILENCODING"];
            $mail->Mailer = "smtp";
            $mail->isHTML(false);
            $mail->From = $PHORUM['system_email_from_address'];
            $mail->Sender = $PHORUM['system_email_from_address'];
            $mail->FromName = $PHORUM['system_email_from_name'];
            if (!isset($settings['host']) || empty($settings['host'])) {
                $settings['host'] = 'localhost';
            }
            if (!isset($settings['port']) || empty($settings['port'])) {
                $settings['port'] = '25';
            }
            $mail->Host = $settings['host'];
            $mail->Port = $settings['port'];
            // set the connection type
            if ($settings['conn'] == 'ssl') {
                $mail->SMTPSecure = "ssl";
            } elseif ($settings['conn'] == 'tls') {
                $mail->SMTPSecure = "tls";
            }
            // smtp-authentication
            if ($settings['auth'] && !empty($settings['username'])) {
                $mail->SMTPAuth = true;
                $mail->Username = $settings['username'];
                $mail->Password = $settings['password'];
            }
            $mail->Body = $message;
            $mail->Subject = $subject;
            // add the newly created message-id
            // in phpmailer as a public var
            $mail->MessageID = $data['messageid'];
            // add custom headers if defined
            if (!empty($data['custom_headers'])) {
                // custom headers in phpmailer are added one by one
                $custom_headers = explode("\n", $data['custom_headers']);
                foreach ($custom_headers as $cheader) {
                    $mail->addCustomHeader($cheader);
                }
            }
            // add attachments if provided
            if (isset($data['attachments']) && count($data['attachments'])) {
                /*
                 * Expected input is an array of
                 *
                 * array(
                 * 'filename'=>'name of the file including extension',
                 * 'filedata'=>'plain (not encoded) content of the file',
                 * 'mimetype'=>'mime type of the file', (optional)
                 * )
                 *
                 */
                foreach ($data['attachments'] as $att_id => $attachment) {
                    $att_type = !empty($attachment['mimetype']) ? $attachment['mimetype'] : 'application/octet-stream';
                    $mail->addStringAttachment($attachment['filedata'], $attachment['filename'], 'base64', $att_type);
                    // try to unset it in the original array to save memory
                    unset($data['attachments'][$att_id]);
                }
            }
            if (!empty($settings['bcc']) && $num_addresses > 3) {
                $bcc = 1;
                $mail->addAddress("undisclosed-recipients:;");
            } else {
                $bcc = 0;
                // lets keep the connection alive - it could be multiple mails
                $mail->SMTPKeepAlive = true;
            }
            foreach ($addresses as $address) {
                if ($bcc) {
                    $mail->addBCC($address);
                } else {
                    $mail->addAddress($address);
                    if (!$mail->send()) {
                        $error_msg = "There was an error sending the message.";
                        $detail_msg = "Error returned was: " . $mail->ErrorInfo;
                        if (function_exists('event_logging_writelog')) {
                            event_logging_writelog(array("source" => "smtp_mail", "message" => $error_msg, "details" => $detail_msg, "loglevel" => EVENTLOG_LVL_ERROR, "category" => EVENTLOG_CAT_MODULE));
                        }
                        if (!isset($settings['show_errors']) || !empty($settings['show_errors'])) {
                            echo $error_msg . "\n";
                            echo $detail_msg;
                        }
                    } elseif (!empty($settings['log_successful'])) {
                        if (function_exists('event_logging_writelog')) {
                            event_logging_writelog(array("source" => "smtp_mail", "message" => "Email successfully sent", "details" => "An email has been sent:\nTo:{$address}\nSubject: {$subject}\nBody: {$message}\n", "loglevel" => EVENTLOG_LVL_INFO, "category" => EVENTLOG_CAT_MODULE));
                        }
                    }
                    // Clear all addresses  for next loop
                    $mail->clearAddresses();
                }
            }
            // bcc needs just one send call
            if ($bcc) {
                if (!$mail->send()) {
                    $error_msg = "There was an error sending the bcc message.";
                    $detail_msg = "Error returned was: " . $mail->ErrorInfo;
                    if (function_exists('event_logging_writelog')) {
                        event_logging_writelog(array("source" => "smtp_mail", "message" => $error_msg, "details" => $detail_msg, "loglevel" => EVENTLOG_LVL_ERROR, "category" => EVENTLOG_CAT_MODULE));
                    }
                    if (!isset($settings['show_errors']) || !empty($settings['show_errors'])) {
                        echo $error_msg . "\n";
                        echo $detail_msg;
                    }
                } elseif (!empty($settings['log_successful'])) {
                    if (function_exists('event_logging_writelog')) {
                        $address_join = implode(",", $addresses);
                        event_logging_writelog(array("source" => "smtp_mail", "message" => "BCC-Email successfully sent", "details" => "An email (bcc-mode) has been sent:\nBCC:{$address_join}\nSubject: {$subject}\nBody: {$message}\n", "loglevel" => EVENTLOG_LVL_INFO, "category" => EVENTLOG_CAT_MODULE));
                    }
                }
            }
            // we have to close the connection with pipelining
            // which is only used in non-bcc mode
            if (!$bcc) {
                $mail->smtpClose();
            }
        } catch (Exception $e) {
            $error_msg = "There was a problem communicating with SMTP";
            $detail_msg = "The error returned was: " . $e->getMessage();
            if (function_exists('event_logging_writelog')) {
                event_logging_writelog(array("source" => "smtp_mail", "message" => $error_msg, "details" => $detail_msg, "loglevel" => EVENTLOG_LVL_ERROR, "category" => EVENTLOG_CAT_MODULE));
            }
            if (!isset($settings['show_errors']) || !empty($settings['show_errors'])) {
                echo $error_msg . "\n";
                echo $detail_msg;
            }
            exit;
        }
    }
    unset($message);
    unset($mail);
    // make sure that the internal mail-facility doesn't kick in
    return 0;
}