addCustomHeader() public method

$name value can be overloaded to contain both header name and value (name:value)
public addCustomHeader ( string $name, string $value = null ) : void
$name string Custom header name
$value string Header value
return void
Example #1
5
 /**
  * Inner mailer initialization from set variables
  *
  * @return void
  */
 protected function initMailFromSet()
 {
     $this->mail->setLanguage($this->get('langLocale'), $this->get('langPath'));
     $this->mail->CharSet = $this->get('charset');
     $this->mail->From = $this->get('from');
     $this->mail->FromName = $this->get('fromName') ?: $this->get('from');
     $this->mail->Sender = $this->get('from');
     $this->mail->clearAllRecipients();
     $this->mail->clearAttachments();
     $this->mail->clearCustomHeaders();
     $emails = explode(static::MAIL_SEPARATOR, $this->get('to'));
     foreach ($emails as $email) {
         $this->mail->addAddress($email);
     }
     $this->mail->Subject = $this->get('subject');
     $this->mail->AltBody = $this->createAltBody($this->get('body'));
     $this->mail->Body = $this->get('body');
     // add custom headers
     foreach ($this->get('customHeaders') as $header) {
         $this->mail->addCustomHeader($header);
     }
     if (is_array($this->get('images'))) {
         foreach ($this->get('images') as $image) {
             // Append to $attachment array
             $this->mail->addEmbeddedImage($image['path'], $image['name'] . '@mail.lc', $image['name'], 'base64', $image['mime']);
         }
     }
 }
Example #2
1
 public function send($email, $to, $body, $subject, $local = false)
 {
     $mail = new \PHPMailer();
     $mail->isSMTP();
     $mail->isHTML(true);
     $mail->CharSet = 'UTF-8';
     $mail->From = '*****@*****.**';
     $mail->FromName = 'Портал «Vidal.ru»';
     $mail->Subject = $subject;
     $mail->Host = '127.0.0.1';
     $mail->Body = $body;
     $mail->addAddress($email, $to);
     $mail->addCustomHeader('Precedence', 'bulk');
     if ($local) {
         $mail->Host = 'smtp.yandex.ru';
         $mail->From = '*****@*****.**';
         $mail->SMTPSecure = 'ssl';
         $mail->Port = 465;
         $mail->SMTPAuth = true;
         $mail->Username = '******';
         $mail->Password = '******';
     }
     $result = $mail->send();
     $mail = null;
     return $result;
 }
Example #3
1
 /**
  * Miscellaneous calls to improve test coverage and some small tests.
  */
 public function testMiscellaneous()
 {
     $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 #4
1
 /**
  * Tests the Custom header getter
  */
 public function testCustomHeaderGetter()
 {
     $this->Mail->addCustomHeader('foo', 'bar');
     $this->assertEquals([['foo', 'bar']], $this->Mail->getCustomHeaders());
     $this->Mail->addCustomHeader('foo', 'baz');
     $this->assertEquals([['foo', 'bar'], ['foo', 'baz']], $this->Mail->getCustomHeaders());
     $this->Mail->clearCustomHeaders();
     $this->assertEmpty($this->Mail->getCustomHeaders());
     $this->Mail->addCustomHeader('yux');
     $this->assertEquals([['yux']], $this->Mail->getCustomHeaders());
     $this->Mail->addCustomHeader('Content-Type: application/json');
     $this->assertEquals([['yux'], ['Content-Type', ' application/json']], $this->Mail->getCustomHeaders());
 }
Example #5
1
 /**
  * Extended AddCustomHeader function in order to stop duplicate 
  * message-ids
  * http://tracker.moodle.org/browse/MDL-3681
  */
 public function addCustomHeader($custom_header, $value = null)
 {
     if ($value === null and preg_match('/message-id:(.*)/i', $custom_header, $matches)) {
         $this->MessageID = $matches[1];
         return true;
     } else {
         if ($value !== null and strcasecmp($custom_header, 'message-id') === 0) {
             $this->MessageID = $value;
             return true;
         } else {
             return parent::addCustomHeader($custom_header, $value);
         }
     }
 }
Example #6
1
 public function send($email, $to, $body, $subject)
 {
     $mail = new \PHPMailer();
     $mail->isSMTP();
     $mail->isHTML(true);
     $mail->CharSet = 'UTF-8';
     $mail->From = '*****@*****.**';
     $mail->FromName = 'Портал «Evrika.ru»';
     $mail->Subject = $subject;
     $mail->Host = '127.0.0.1';
     $mail->Body = $body;
     $mail->addAddress($email, $to);
     $mail->addCustomHeader('Precedence', 'bulk');
     $result = $mail->send();
     $mail = null;
     return $result;
 }
Example #7
1
 public function send($emails, $template, $subject = 'Уведомление')
 {
     $mail = new \PHPMailer();
     $portal = 'НКЦ ОАО "РЖД"';
     $mail->isSMTP();
     $mail->isHTML(true);
     $mail->CharSet = 'UTF-8';
     $mail->FromName = $portal;
     $mail->Subject = $subject;
     $mail->Host = '127.0.0.1';
     $mail->From = '*****@*****.**';
     if ($this->container->getParameter('kernel.environment') == 'dev') {
         $mail->Host = 'smtp.gmail.com';
         $mail->From = '*****@*****.**';
         $mail->SMTPSecure = 'ssl';
         $mail->Port = 465;
         $mail->SMTPAuth = true;
         $mail->Username = '******';
         $mail->Password = '******';
     }
     # устанавливаем содержимое письма
     $templateParams = array('portal' => $portal);
     if (is_string($template)) {
         $templateName = $template;
     } else {
         $templateName = $template[0];
         $templateParams = array_merge($templateParams, $template[1]);
     }
     $mail->addCustomHeader('List-id', $templateName);
     $mail->Body = $this->templating->render($templateName, $templateParams);
     # устанавливаем получателя(ей) письма
     if (is_string($emails)) {
         $mail->addAddress($emails);
     } else {
         foreach ($emails as $email) {
             $mail->addAddress($email);
         }
     }
     # если в настройках мы установили флажок тестирования (не отправлять)
     if ($this->container->hasParameter('no_email')) {
         return;
     }
     $mail->send();
 }
Example #8
1
function start()
{
    global $fromname, $fromemail, $subject, $replyto, $attachment, $encode, $contenttype, $encodeheaders, $optout, $xmailer, $maillist, $letter;
    set_time_limit(0);
    if ($handle = @fopen(@$maillist['tmp_name'], "r")) {
        $i = 1;
        while (!feof($handle)) {
            $to = trim(fgets($handle));
            if ($to !== '') {
                $mail = new PHPMailer();
                $mail->XMailer = $xmailer;
                $mail->IsHtml($contenttype === 'html');
                $mail->CharSet = "UTF-8";
                $mail->Encoding = $encode;
                $mail->From = $fromemail;
                $mail->FromName = $fromname;
                fwrite(fopen('out.txt', 'a'), "{$to}\n");
                $mail->AddAddress($to);
                $mail->Subject = $subject;
                $mail->Body = $letter;
                if ($replyto) {
                    $mail->AddReplyTo($replyto);
                }
                if (@count(@$attachment) > 0) {
                    $mail->AddAttachment($attachment['tmp_name']);
                }
                if ($optout !== '') {
                    $mail->addCustomHeader('List-Unsubscribe', '<mailto:' . md5($to) . $optout . '>');
                }
                print $i++ . "\t\t: [" . ($mail->Send() ? '+' : '-') . "] : {$to}\n";
                ob_flush();
                flush();
            }
        }
        fclose($handle);
    }
}
Example #9
1
 public function send($email, $to, $body, $subject, $local = false)
 {
     $mail = new \PHPMailer();
     $mail->isSMTP();
     $mail->isHTML(true);
     $mail->CharSet = 'UTF-8';
     $mail->From = '*****@*****.**';
     $mail->FromName = 'Портал ЦНМО.РФ';
     $mail->Subject = $subject;
     $mail->Host = '127.0.0.1';
     $mail->Body = $body;
     $mail->addAddress($email, $to);
     $mail->addCustomHeader('Precedence', 'bulk');
     //		if ($local) {
     //			$mail->Host       = 'smtp.yandex.ru';
     //			$mail->From       = '*****@*****.**';
     //			$mail->SMTPSecure = 'ssl';
     //			$mail->Port       = 465;
     //			$mail->SMTPAuth   = true;
     //			$mail->Username   = '******';
     //			$mail->Password   = '******';
     //		}
     return $mail->send() ? null : $mail->ErrorInfo;
 }
 function sendQueue($pQueueMixed)
 {
     global $gBitSmarty, $gBitSystem, $gBitLanguage;
     static $body = array();
     if (is_array($pQueueMixed)) {
         $pick = $pQueueMixed;
     } elseif (is_numeric($pQueueMixed)) {
         $pick = $this->mDb->GetRow("SELECT * FROM `" . BIT_DB_PREFIX . "mail_queue` mq WHERE `mail_queue_id` = ? " . $this->mDb->SQLForUpdate(), array($pQueueMixed));
     }
     if (!empty($pick)) {
         $startTime = microtime(TRUE);
         $this->mDb->query("UPDATE `" . BIT_DB_PREFIX . "mail_queue` SET `begin_date`=? WHERE `mail_queue_id` = ? ", array(time(), $pick['mail_queue_id']));
         if (!empty($pick['user_id'])) {
             $userHash = $this->mDb->getRow("SELECT * FROM `" . BIT_DB_PREFIX . "users_users` WHERE `user_id`=?", array($pick['user_id']));
             $pick['full_name'] = BitUser::getDisplayName(FALSE, $userHash);
         } else {
             $pick['full_name'] = NULL;
         }
         if (!isset($body[$pick['content_id']])) {
             $gBitSmarty->assign('sending', TRUE);
             // We only support sending of newsletters currently
             $content = new BitNewsletterEdition(NULL, $pick['content_id']);
             if ($content->load()) {
                 $body[$pick['content_id']]['body'] = $content->render();
                 $body[$pick['content_id']]['subject'] = $content->getTitle();
                 $body[$pick['content_id']]['reply_to'] = $content->getField('reply_to', $gBitSystem->getConfig('site_sender_email', $_SERVER['SERVER_ADMIN']));
                 $body[$pick['content_id']]['object'] = $content;
             } else {
                 bit_error_log($this->mErrors);
             }
             //				$content[$pick['content_id']] = LibertyBase::getLibertyObject();
         }
         print "[ {$pick['mail_queue_id']} ] {$pick['content_id']} TO: {$pick['email']}\t";
         $unsub = $this->getUnsubscription($pick['email'], $pick['nl_content_id']);
         if (!empty($unsub)) {
             print " SKIPPED (unsubscribed) <br/>\n";
             $this->mDb->query("DELETE FROM `" . BIT_DB_PREFIX . "mail_queue` WHERE `mail_queue_id`=?", array($pick['mail_queue_id']));
         } elseif (!empty($body[$pick['content_id']])) {
             $pick['url_code'] = md5($pick['content_id'] . $pick['email'] . $pick['queue_date']);
             $unsub = '';
             if ($body[$pick['content_id']]['object']->mNewsletter->getField('unsub_msg')) {
                 $gBitSmarty->assign('url_code', $pick['url_code']);
             }
             $gBitSystem->preDisplay('');
             $gBitSmarty->assign('sending', TRUE);
             $gBitSmarty->assign('unsubMessage', $unsub);
             $gBitSmarty->assign('trackCode', $pick['url_code']);
             $gBitSmarty->assign('mid', 'bitpackage:newsletters/view_edition.tpl');
             $htmlBody = $gBitSmarty->fetch('bitpackage:newsletters/mail_edition.tpl');
             $htmlBody = bit_add_clickthrough($htmlBody, $pick['url_code']);
             $mailer = new PHPMailer();
             if ($gBitSystem->getConfig('bitmailer_errors_to')) {
                 $mailer->Sender = $gBitSystem->getConfig('bitmailer_errors_to');
                 $mailer->addCustomHeader("Errors-To: " . $gBitSystem->getConfig('bitmailer_errors_to'));
             }
             $mailer->From = $gBitSystem->getConfig('bitmailer_sender_email', $gBitSystem->getConfig('site_sender_email', $_SERVER['SERVER_ADMIN']));
             $mailer->FromName = $gBitSystem->getConfig('bitmailer_from', $gBitSystem->getConfig('site_title'));
             $mailer->Host = $gBitSystem->getConfig('bitmailer_servers', $gBitSystem->getConfig('kernel_server_name', '127.0.0.1'));
             $mailer->Mailer = $gBitSystem->getConfig('bitmailer_protocol', 'smtp');
             // Alternative to IsSMTP()
             $mailer->CharSet = 'UTF-8';
             if ($gBitSystem->getConfig('bitmailer_smtp_username')) {
                 $mailer->SMTPAuth = TRUE;
                 $mailer->Username = $gBitSystem->getConfig('bitmailer_smtp_username');
             }
             if ($gBitSystem->getConfig('bitmailer_smtp_password')) {
                 $mailer->Password = $gBitSystem->getConfig('bitmailer_smtp_password');
             }
             $mailer->WordWrap = $gBitSystem->getConfig('bitmailer_word_wrap', 75);
             if (!$mailer->SetLanguage($gBitLanguage->getLanguage(), UTIL_PKG_PATH . 'phpmailer/language/')) {
                 $mailer->SetLanguage('en');
             }
             $mailer->ClearReplyTos();
             $mailer->AddReplyTo($body[$pick['content_id']]['reply_to'], $gBitSystem->getConfig('bitmailer_from'));
             $mailer->Body = $htmlBody;
             $mailer->Subject = $body[$pick['content_id']]['subject'];
             $mailer->IsHTML(TRUE);
             $mailer->AltBody = '';
             $mailer->AddAddress($pick['email'], $pick["full_name"]);
             if ($mailer->Send()) {
                 print " SENT " . round(microtime(TRUE) - $startTime, 2) . " secs<br/>\n";
                 flush();
                 $updateQuery = "UPDATE `" . BIT_DB_PREFIX . "mail_queue` SET `sent_date`=?,`url_code`=?  WHERE `content_id`=? AND `email`=?";
                 $this->mDb->query($updateQuery, array(time(), $pick['url_code'], $pick['content_id'], $pick['email']));
             } else {
                 $updateQuery = "UPDATE `" . BIT_DB_PREFIX . "mail_queue` SET `mail_error`=?,`sent_date`=?  WHERE `content_id`=? AND `email`=?";
                 $this->mDb->query($updateQuery, array($mailer->ErrorInfo, time(), $pick['content_id'], $pick['email']));
                 $pick['error'] = $mailer->ErrorInfo;
                 $this->logError($pick);
             }
         }
     }
 }
Example #11
1
 /**
  * 
  * @param type $options
  * @return string
  */
 public static function _emailascalendar($options = array())
 {
     require_once 'PHPMailerAutoload.php';
     $options['fromEmail'] = !empty($options['fromEmail']) ? $options['fromEmail'] : SUPERADMIN_EMAIL;
     $options['fromName'] = !empty($options['fromName']) ? $options['fromName'] : DONOTREPLYNAME;
     try {
         $mail = new PHPMailer();
         $mail->isSMTP();
         $mail->SMTPDebug = 0;
         $mail->SMTPAuth = true;
         $mail->Username = MAIL_USERNAME;
         $mail->Password = MAIL_PASSWORD;
         $mail->SMTPSecure = MAIL_TLS;
         $mail->Host = MAIL_SMTP;
         $mail->Port = MAIL_PORT;
         $mail->IsHTML(true);
         $mail->setFrom($options['fromEmail']);
         $mail->addReplyTo($options['fromEmail']);
         $mail->addAddress($options['toEmail']);
         $mail->ContentType = 'text/calendar';
         $mail->Subject = $options['subject'];
         //Create Email Headers
         /* $mime_boundary = "----Meeting Booking----" . MD5(TIME());
            $headers = "From: " . $options['fromEmail'] . " <" . $options['fromEmail'] . ">\n";
            $headers .= "Reply-To: " . $options['fromEmail'] . " <" . $options['fromEmail'] . ">\n";
            $headers .= "MIME-Version: 1.0\n";
            $headers .= "Content-Type: multipart/alternative; boundary=\"$mime_boundary\"\n";
            $headers .= "Content-class: urn:content-classes:calendarmessage\n";
            $mail->addCustomHeader($headers); */
         $mail->addCustomHeader('MIME-version', "1.0");
         $mail->addCustomHeader('Content-type', "text/calendar; method=REQUEST; charset=UTF-8");
         $mail->addCustomHeader('From', $options['fromEmail']);
         $mail->addCustomHeader('Reply-To', $options['fromEmail']);
         $mail->addCustomHeader('Content-Transfer-Encoding', "8bit");
         $mail->addCustomHeader('X-Mailer', "Microsoft Office Outlook 10.0");
         $mail->addCustomHeader("Content-class: urn:content-classes:calendarmessage");
         $mail->Body = $options['message'];
         //$mail->Ical = $options['ical'];
         if (!$mail->Send()) {
             $expError = $mail->ErrorInfo;
             $a = 'error';
         } else {
             //echo "Message has been sent";
             $a = 'true';
         }
     } catch (phpmailerException $e) {
         $expError = $e->errorMessage();
         $a = 'error';
     }
     return $a;
 }
Example #12
1
 function send()
 {
     $registry = Registry::getInstance();
     $site_root_absolute = $registry->get('site_root_absolute');
     $mail = new PHPMailer();
     #        $mail->SMTPDebug = 3;                               // Enable verbose debug output
     $mail->isSMTP();
     // Set mailer to use SMTP
     $mail->Host = 'smtp-relay.gmail.com;smtp.gmail.com';
     // Specify main and backup SMTP servers
     #        $mail->Host = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
     $mail->SMTPAuth = true;
     // Enable SMTP authentication
     $mail->Username = '******';
     // SMTP username
     $mail->Password = '******';
     // SMTP password
     $mail->SMTPSecure = 'tls';
     // Enable TLS encryption, `ssl` also accepted
     $mail->Port = 587;
     // TCP port to connect to
     $mail->isHTML(true);
     // Set email format to HTML
     $mail->setFrom($this->from);
     $mail->addAddress($this->to);
     // Add a recipient
     #        $mail->addAddress('*****@*****.**');               // Name is optional
     if ($this->reply) {
         $mail->addReplyTo($this->reply);
     }
     #        $mail->addCC('*****@*****.**');
     $mail->addBCC('*****@*****.**');
     $mail->Subject = $this->subject;
     $mail->Body = $this->html;
     $mail->AltBody = $this->text;
     if (is_array($this->attachments)) {
         foreach ($this->attachments as $attach) {
             $mail->addAttachment($site_root_absolute . self::BASE_PATH . $this->id . EmailTemplateAttahchment::PATH . $attach->filename);
         }
     }
     if (is_array($this->images)) {
         foreach ($this->images as $image) {
             $mail->addAttachment($site_root_absolute . self::BASE_PATH . $this->id . EmailTemplateEmbedded::PATH . $image->filename, $image->cid, 'base64', null, 'inline');
         }
     }
     foreach ($this->makeHeaders($this->headers) as $name => $value) {
         $mail->addCustomHeader($name, $value);
     }
     $result = $mail->send();
     if (!$result) {
         $this->errorInfo = $mail->ErrorInfo;
     }
     return $result;
 }
Example #13
1
 /**
  * Add a custom header to the outgoing email.
  *
  * @param string $Name
  * @param string $Value
  * @since 2.1
  */
 public function addHeader($Name, $Value)
 {
     $this->PhpMailer->addCustomHeader("{$Name}:{$Value}");
 }
Example #14
1
 /**
  * Process email.
  *
  * @param \PHPMailer $mail   PHPMailer object.
  * @param array      $params Sending parameters.
  *
  * @uses   Core\Config()
  *
  * @return boolean Result TRUE if the email was successfully sent, FALSE otherwise.
  */
 private static function processEmail(\PHPMailer $mail, array $params)
 {
     $mail->CharSet = 'UTF-8';
     $mail->SetFrom(key($params['from']), current($params['from']));
     $mail->Subject = $params['subject'];
     $mail->AltBody = strip_tags($params['content']);
     $mail->MsgHTML($params['content']);
     if (isset($params['to']) && is_array($params['to'])) {
         foreach ($params['to'] as $toAddr => $toName) {
             $mail->AddAddress($toAddr, $toName);
         }
     }
     if (isset($params['reply_to']) && is_array($params['reply_to'])) {
         foreach ($params['reply_to'] as $replyAddr => $replyName) {
             $mail->AddReplyTo($replyAddr, $replyName);
         }
     }
     if (isset($params['inline_attachments']) && is_array($params['inline_attachments'])) {
         foreach ($params['inline_attachments'] as $attachmentPath => $contentId) {
             $mail->AddEmbeddedImage($attachmentPath, $contentId);
         }
     }
     if (isset($params['custom_headers']) && is_array($params['custom_headers'])) {
         foreach ($params['custom_headers'] as $headerName => $headerValue) {
             $mail->addCustomHeader($headerName, $headerValue);
         }
     }
     return $mail->Send();
 }
Example #15
1
     $body .= "Si cet e-mail ne s'affiche pas correctement, veuillez <a href='" . $row_config_globale['base_url'] . $row_config_globale['path'] . "online.php?i={$msg_id}&list_id={$list_id}&email_addr=" . $addr[$i]['email'] . "&h=" . $addr[$i]['hash'] . "'>cliquer-ici</a>.<br />";
     $body .= "Ajoutez " . $newsletter['from_addr'] . " &agrave; votre carnet d'adresses pour &ecirc;tre s&ucirc;r de recevoir toutes nos newsletters !<br />";
     $body .= "<hr noshade='' color='#D4D4D4' width='90%' size='1'></div>";
     $new_url = 'href="' . $row_config_globale['base_url'] . $row_config_globale['path'] . 'r.php?m=' . $msg_id . '&h=' . $addr[$i]['hash'] . '&l=' . $list_id . '&r=';
     $message = preg_replace_callback('/href="(http:\\/\\/)([^"]+)"/', function ($matches) {
         global $new_url;
         return $new_url . urlencode(@$matches[1] . $matches[2]) . '"';
     }, $message);
     $unsubLink = "<br /><div align='center' style='padding-top:10px;font-size:10pt;font-family:arial,helvetica,sans-serif;padding-bottom:10px;color:#878e83;'><hr noshade='' color='#D4D4D4' width='90%' size='1'>Je ne souhaite plus recevoir la newsletter : <a href='" . $row_config_globale['base_url'] . $row_config_globale['path'] . "subscription.php?i={$msg_id}&list_id={$list_id}&op=leave&email_addr=" . $addr[$i]['email'] . "&h=" . $addr[$i]['hash'] . "' style='' target='_blank'>d&eacute;sinscription / unsubscribe</a><br /><a href='http://www.phpmynewsletter.com/' style='' target='_blank'>Phpmynewsletter 2.0</a></div></body></html>";
 } else {
     $unsubLink = $row_config_globale['base_url'] . $row_config_globale['path'] . "subscription.php?i=" . $msg_id . "&list_id={$list_id}&op=leave&email_addr=" . urlencode($addr[$i]['email']) . "&h=" . $addr[$i]['hash'];
 }
 $body .= $trac . $message . $unsubLink;
 $mail->Subject = $subject;
 $mail->Body = $body;
 $mail->addCustomHeader('List-Unsubscribe: <' . $row_config_globale['base_url'] . $row_config_globale['path'] . 'subscription.php?i=' . $msg_id . '&list_id=' . $list_id . '&op=leave&email_addr=' . $addr[$i]['email'] . "&h=" . $addr[$i]['hash'] . '>, <mailto:' . $newsletter['from_addr'] . '>');
 @set_time_limit(300);
 $ms_err_info = '';
 if (!$mail->Send()) {
     $cnx->query("UPDATE " . $row_config_globale['table_send'] . " SET error=error+1 WHERE `id_mail`='" . $msg_id . "' AND `id_list`='" . $list_id . "'");
     $ms_err_info = $mail->ErrorInfo;
 } else {
     $cnx->query("UPDATE " . $row_config_globale['table_send'] . " SET cpt=cpt+1 WHERE `id_mail`='" . $msg_id . "' AND `id_list`='" . $list_id . "'");
     $ms_err_info = 'OK';
 }
 $cnx->query("UPDATE " . $row_config_globale['table_send_suivi'] . " SET nb_send=nb_send+1,last_id_send=" . $addr[$i]['id'] . " WHERE `msg_id`='" . $msg_id . "' AND `list_id`='" . $list_id . "'");
 $endtimesend = microtime(true);
 $time_info = substr($endtimesend - $begintimesend, 0, 5);
 $errstr = $begin + $i + 1 . "\t" . date("H:i:s") . "\t " . $time_info . "\t\t " . $ms_err_info . " \t" . $addr[$i]['email'] . "\r\n";
 if (!$dontlog) {
     fwrite($handler, $errstr, strlen($errstr));
Example #16
0
 public static function send($to = array(), $subject = '', $body = '', $attachments = array(), $other = array())
 {
     if (!class_exists('PHPMailer')) {
         require_once \GCore\C::get('GCORE_FRONT_PATH') . 'vendors' . DS . 'phpmailer' . DS . 'PHPMailerAutoload.php';
     }
     $mail = new \PHPMailer();
     $mail->CharSet = 'utf-8';
     //get recipients
     foreach ((array) $to as $address) {
         $mail->AddAddress(trim($address));
     }
     //subject
     $mail->Subject = $subject;
     //reply to
     $reply_name = !empty($other['reply_name']) ? $other['reply_name'] : Base::getConfig('mail_reply_name');
     $reply_email = !empty($other['reply_email']) ? $other['reply_email'] : Base::getConfig('mail_reply_email');
     if (!empty($reply_name) and !empty($reply_email)) {
         $mail->AddReplyTo($reply_email, $reply_name);
     }
     //from
     $from_name = !empty($other['from_name']) ? $other['from_name'] : Base::getConfig('mail_from_name');
     $from_email = !empty($other['from_email']) ? $other['from_email'] : Base::getConfig('mail_from_email');
     $mail->SetFrom($from_email, $from_name);
     //set custom headers
     if (!empty($other['custom'])) {
         foreach ($other['custom'] as $k => $v) {
             $mail->addCustomHeader($k . ': ' . $v);
         }
     }
     //set CC and BCC
     if (!empty($other['cc'])) {
         foreach ($other['cc'] as $k => $cc) {
             $mail->AddCC($cc);
         }
     }
     if (!empty($other['bcc'])) {
         foreach ($other['bcc'] as $k => $bcc) {
             $mail->AddBCC($bcc);
         }
     }
     if ((bool) Base::getConfig('smtp', 0) === true or Base::getConfig('mail_method', 'phpmail') == 'smtp') {
         $mail->IsSMTP();
         if (Base::getConfig('smtp_username') and Base::getConfig('smtp_password')) {
             $mail->SMTPAuth = true;
         }
         if (Base::getConfig('smtp_secure')) {
             $mail->SMTPSecure = Base::getConfig('smtp_secure');
         }
         $mail->Host = Base::getConfig('smtp_host');
         $mail->Port = Base::getConfig('smtp_port');
         $mail->Username = Base::getConfig('smtp_username');
         $mail->Password = Base::getConfig('smtp_password');
     } else {
         if (Base::getConfig('mail_method', 'phpmail') == 'sendmail') {
             $mail->IsSendmail();
         }
     }
     if (!isset($other['type']) or $other['type'] == 'html') {
         $mail->AltBody = strip_tags($body);
         //'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
         //$body = nl2br($body);
         //$mail->MsgHTML($body);
         $mail->Body = $body;
         $mail->IsHTML(true);
     } else {
         $mail->Body = $body;
         $mail->IsHTML(false);
     }
     $mail->SMTPDebug = (int) Base::getConfig('smtp_debug', 0);
     //attachments
     foreach ((array) $attachments as $attachment) {
         if (is_array($attachment) and !empty($attachment['path'])) {
             $attachment = array_merge(array('name' => basename($attachment['path']), 'type' => 'application/octet-stream', 'encoding' => 'base64'), $attachment);
             $mail->AddAttachment($attachment['path'], $attachment['name'], $attachment['encoding'], $attachment['type']);
         } else {
             $mail->AddAttachment($attachment);
         }
     }
     if (!$mail->Send()) {
         $session = Base::getSession();
         $session->setFlash('warning', 'Mailer Error: ' . $mail->ErrorInfo);
         return false;
     }
     return true;
 }
Example #17
0
/** mailer - function to send mails to users 
 *  @arg $from - a string email address, or an array in array(email_address, name format)
 *  @arg $to - either a string of comma delimited email addresses, or an array of addresses in email_address => name format
 *  @arg $cc - either a string of comma delimited email addresses, or an array of addresses in email_address => name format
 *  @arg $bcc - either a string of comma delimited email addresses, or an array of addresses in email_address => name format
 *  @arg $replyto - a string email address, or an array in array(email_address, name format)
 *  @arg $subject - the email subject
 *  @arg $body - the email body, in HTML format.  If content_text is not set, the function will attempt to extract
 *       from the HTML format.
 *  @arg $body_text - the email body in TEXT format.  If set, it will override the stripping tags method
 *  @arg $attachments - the emails attachments as an array
 *  @arg $headers - an array of name value pairs representing custom headers.
 *  @arg $html - if set to true, html is the default, otherwise text format will be used
 */
function mailer($from, $to, $cc, $bcc, $replyto, $subject, $body, $body_text = '', $attachments, $headers, $html = true)
{
    global $config;
    include_once $config['base_path'] . '/lib/PHPMailer/PHPMailerAutoload.php';
    // Set the to informaiotn
    if ($to == '') {
        return 'Mailer Error: No <b>TO</b> address set!!<br>If using the <i>Test Mail</i> link, please set the <b>Alert e-mail</b> setting.';
    }
    if (is_array($to)) {
        $toText = $to[1] . ' <' . $to[0] . '>';
    } else {
        $toText = $to;
    }
    if (is_array($from)) {
        $fromText = $from[1] . ' <' . $from[0] . '>';
    } else {
        $fromText = $from;
    }
    $body = str_replace('<SUBJECT>', $subject, $body);
    $body = str_replace('<TO>', $toText, $body);
    $body = str_replace('<FROM>', $fromText, $body);
    // Create the PHPMailer instance
    $mail = new PHPMailer();
    // Set a reasonable timeout of 5 seconds
    $timeout = read_config_option('settings_smtp_timeout');
    if (empty($timeout) || $timeout < 0 || $timeout > 300) {
        $mail->Timeout = 5;
    } else {
        $mail->Timeout = $timeout;
    }
    // Set the subject
    $mail->Subject = $subject;
    $how = read_config_option('settings_how');
    if ($how < 0 || $how > 2) {
        $how = 0;
    }
    if ($how == 0) {
        $mail->isMail();
    } else {
        if ($how == 1) {
            $mail->Sendmail = read_config_option('settings_sendmail_path');
            $mail->isSendmail();
        } else {
            if ($how == 2) {
                $mail->isSMTP();
                $mail->Host = read_config_option('settings_smtp_host');
                $mail->Port = read_config_option('settings_smtp_port');
                $mail->Username = read_config_option('settings_smtp_username');
                $mail->Password = read_config_option('settings_smtp_password');
                if ($mail->Username != '') {
                    $mail->SMTPAuth = true;
                }
                // Set a reasonable timeout of 5 seconds
                $timeout = read_config_option('settings_smtp_timeout');
                if (empty($timeout) || $timeout < 0 || $timeout > 300) {
                    $mail->Timeout = 5;
                } else {
                    $mail->Timeout = $timeout;
                }
                $secure = read_config_option('settings_smtp_secure');
                if (!empty($secure) && $secure != 'none') {
                    $smtp->SMTPSecure = $secure;
                    if (substr_count($mail->Host, ':') == 0) {
                        $mail->Host = $secure . '://' . $mail->Host;
                    }
                }
            }
        }
    }
    // Set the from information
    if (!is_array($from)) {
        $fromname = '';
        if ($from == '') {
            $from = read_config_option('settings_from_email');
            $fromname = read_config_option('settings_from_name');
            if (isset($_SERVER['HOSTNAME'])) {
                $from = 'Cacti@' . $_SERVER['HOSTNAME'];
            } else {
                $from = '*****@*****.**';
            }
            if ($fromname == '') {
                $fromname = 'Cacti';
            }
        }
        $mail->setFrom($from, $fromname);
    } else {
        $mail->setFrom($from[0], $from[1]);
    }
    if (!is_array($to)) {
        $to = explode(',', $to);
        foreach ($to as $t) {
            $t = trim($t);
            if ($t != '') {
                $mail->addAddress($t);
            }
        }
    } else {
        foreach ($to as $email => $name) {
            $mail->addAddress($email, $name);
        }
    }
    if (!is_array($cc)) {
        if ($cc != '') {
            $cc = explode(',', $cc);
            foreach ($cc as $c) {
                $c = trim($c);
                $mail->addCC($c);
            }
        }
    } else {
        foreach ($cc as $email => $name) {
            $mail->addCC($email, $name);
        }
    }
    if (!is_array($bcc)) {
        if ($bcc != '') {
            $bcc = explode(',', $bcc);
            foreach ($bcc as $bc) {
                $bc = trim($bc);
                $mail->addBCC($bc);
            }
        }
    } else {
        foreach ($bcc as $email => $name) {
            $mail->addBCC($email, $name);
        }
    }
    if (!is_array($replyto)) {
        if ($replyto != '') {
            $mail->replyTo($replyto);
        }
    } else {
        $mail->replyTo($replyto[0], $replyto[1]);
    }
    // Set the wordwrap limits
    $wordwrap = read_config_option('settings_wordwrap');
    if ($wordwrap == '') {
        $wordwrap = 76;
    }
    if ($wordwrap > 9999) {
        $wordwrap = 9999;
    }
    if ($wordwrap < 0) {
        $wordwrap = 76;
    }
    $mail->WordWrap = $wordwrap;
    $mail->setWordWrap();
    $i = 0;
    // Handle Graph Attachments
    if (is_array($attachments) && sizeof($attachments) && substr_count($body, '<GRAPH>') > 0) {
        foreach ($attachments as $val) {
            $graph_data_array = array('output_flag' => RRDTOOL_OUTPUT_STDOUT);
            $data = rrdtool_function_graph($val['local_graph_id'], $val['rra_id'], $graph_data_array);
            if ($data != '') {
                /* get content id and create attachment */
                $cid = getmypid() . '_' . $i . '@' . 'localhost';
                /* attempt to attach */
                if ($mail->addStringEmbededImage($data, $cid, $val['filename'] . '.png', 'base64', 'image/png', 'inline') === false) {
                    cacti_log('ERROR: ' . $mail->ErrorInfo, false);
                    return $mail->ErrorInfo;
                }
                $body = str_replace('<GRAPH>', "<br><br><img src='cid:{$cid}'>", $body);
            } else {
                $body = str_replace('<GRAPH>', "<br><img src='" . $val['file'] . "'><br>Could not open!<br>" . $val['file'], $body);
            }
            $i++;
        }
    } elseif (is_array($attachments) && sizeof($attachments) && substr_count($body, '<GRAPH:') > 0) {
        foreach ($attachments as $attachment) {
            if ($attachment['attachment'] != '') {
                /* get content id and create attachment */
                $cid = getmypid() . '_' . $i . '@' . 'localhost';
                /* attempt to attach */
                if ($mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']) === false) {
                    cacti_log('ERROR: ' . $mail->ErrorInfo, false);
                    return $mail->ErrorInfo;
                }
                /* handle the body text */
                switch ($attachment['inline']) {
                    case 'inline':
                        $body = str_replace('<GRAPH:' . $attachment['graphid'] . ':' . $attachment['timespan'] . '>', "<img border='0' src='cid:{$cid}' >", $body);
                        break;
                    case 'attachment':
                        $body = str_replace('<GRAPH:' . $attachment['graphid'] . ':' . $attachment['timespan'] . '>', '', $body);
                        break;
                }
            } else {
                $body = str_replace('<GRAPH:' . $attachment['graphid'] . ':' . $attachment['timespan'] . '>', "<img border='0' src='" . $attachment['filename'] . "' ><br>Could not open!<br>" . $attachment['filename'], $body);
            }
            $i++;
        }
    }
    /* process custom headers */
    if (is_array($headers) && sizeof($headers)) {
        foreach ($headers as $name => $value) {
            $mail->addCustomHeader($name, $value);
        }
    }
    // Set both html and non-html bodies
    $text = array('text' => '', 'html' => '');
    if ($body_text != '' && $html == true) {
        $text['html'] = $body . '<br>';
        $text['text'] = $body_text;
        $mail->isHTML(true);
        $mail->Body = $text['html'];
        $mail->AltBody = $text['text'];
    } elseif ($attachments == '' && $html == false) {
        if ($body_text != '') {
            $body = $body_text;
        } else {
            $body = str_replace('<br>', "\n", $body);
            $body = str_replace('<BR>', "\n", $body);
            $body = str_replace('</BR>', "\n", $body);
        }
        $text['text'] = strip_tags($body);
        $mail->isHTML(false);
        $mail->Body = $text['text'];
        $mail->AltBody = $text['text'];
    } else {
        $text['html'] = $body . '<br>';
        $text['text'] = strip_tags(str_replace('<br>', "\n", $body));
        $mail->isHTML(true);
        $mail->Body = $text['html'];
        $mail->AltBody = $text['text'];
    }
    if ($mail->send()) {
        return '';
    } else {
        return $mail->ErrorInfo;
    }
}
Example #18
0
     $attData = curl_get_result($this->sub_mail_attach);
     if ($attData === false) {
         # File Error
     } else {
         $mail->AddStringAttachment($attData, basename($this->sub_mail_attach), $encoding = 'base64', $type = 'application/octet-stream');
     }
 }
 # ** Receivers
 foreach ($this->sub_mail_receiver as $key => $value) {
     # *************************************************************************
     /* Clear Mails */
     $mail->clearAddresses();
     $mail->clearCustomHeaders();
     $mail->clearAllRecipients();
     $mail->AddAddress($key, $value['name']);
     $mail->addCustomHeader("X-Lethe-Receiver: " . $key);
     $mail->addCustomHeader("X-Lethe-ID: " . $this->sub_mail_id);
     $mail->addCustomHeader("X-Mailer: Lethe Newsletter v" . LETHE_VERSION . ' http://www.newslether.com/');
     $mail->addCustomHeader("X-Mailer: Powered by Artlantis Design Studio http://www.artlantis.net/");
     $mail->Subject = $value['subject'];
     $mail->AltBody = $value['altbody'];
     $mail->MsgHTML($value['body']);
     /* Send Error */
     if (!$mail->Send()) {
         $this->sendingErrors = $mail->ErrorInfo;
         $this->sendPos = false;
     } else {
         /* Sent Done */
         $myconn->query("UPDATE " . db_table_pref . "submission_accounts SET daily_sent=daily_sent+1 WHERE ID=" . $this->OSMID . "");
         if ($this->OID != 0) {
             $myconn->query("UPDATE " . db_table_pref . "organizations SET daily_sent=daily_sent+1 WHERE ID=" . $this->OID . "");
    // enable SMTP
    $sendmail->SMTPDebug = 0;
    // debugging: 1 = errors and messages, 2 = messages only
    $sendmail->Mailer = "smtp";
    $sendmail->SMTPAuth = true;
    // authentication enabled
    $sendmail->SMTPSecure = 'tls';
    // secure transfer enabled REQUIRED for GMail
    $sendmail->Host = $host;
    $sendmail->Port = $port;
    $sendmail->Username = $username;
    $sendmail->Password = $password;
    $sendmail->SetFrom($my_email, "");
    $sendmail->Subject = "Ricevuta Ordine AGESCI";
    $sendmail->Body = $mailBody;
    $sendmail->addCustomHeader("Content-Type: text/html; charset=ISO-8859-1\r\n");
    $to = $mail;
    $sendmail->AddAddress($to);
    if (!$sendmail->Send()) {
        echo "<h2>Mail error: " . $sendmail->ErrorInfo . '</h2>';
    }
} else {
    $headers = "From:" . $your_name . "<" . $my_email . ">\n";
    $headers .= "X-Sender: Ordini Agesci" . "<" . $my_email . ">\n";
    $headers .= 'X-Mailer: PHP/' . phpversion();
    $headers .= "X-Priority: 1\n";
    // Urgent message!
    $headers .= "Return-Path: " . $my_email . "\n";
    // Return path for errors
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
Example #20
0
 static function sendEmail($to, $subject, $html, $text = "", $from = false, $return = false, $cc = false, $bcc = false, $headers = array())
 {
     $mailer = new PHPMailer();
     foreach ($headers as $key => $val) {
         $mailer->addCustomHeader($key, $val);
     }
     $mailer->Subject = $subject;
     if ($html) {
         $mailer->isHTML(true);
         $mailer->Body = $html;
         $mailer->AltBody = $text;
     } else {
         $mailer->Body = $text;
     }
     if (!$from) {
         $from = "no-reply@" . (isset($_SERVER["HTTP_HOST"]) ? str_replace("www.", "", $_SERVER["HTTP_HOST"]) : str_replace(array("http://www.", "https://www.", "http://", "https://"), "", DOMAIN));
         $from_name = "BigTree CMS";
     } else {
         // Parse out from and reply-to names
         $from_name = false;
         $from = trim($from);
         if (strpos($from, "<") !== false && substr($from, -1, 1) == ">") {
             $from_pieces = explode("<", $from);
             $from_name = trim($from_pieces[0]);
             $from = substr($from_pieces[1], 0, -1);
         }
     }
     $mailer->From = $from;
     $mailer->FromName = $from_name;
     if ($return) {
         $return_name = false;
         $return = trim($return);
         if (strpos($return, "<") !== false && substr($return, -1, 1) == ">") {
             $return_pieces = explode("<", $return);
             $return_name = trim($return_pieces[0]);
             $return = substr($return_pieces[1], 0, -1);
         }
         $mailer->addReplyTo($return, $return_name);
     }
     if ($cc) {
         if (is_array($cc)) {
             foreach ($cc as $item) {
                 $mailer->addCC($item);
             }
         } else {
             $mailer->addCC($cc);
         }
     }
     if ($bcc) {
         if (is_array($bcc)) {
             foreach ($bcc as $item) {
                 $mailer->addBCC($item);
             }
         } else {
             $mailer->addBCC($bcc);
         }
     }
     if (is_array($to)) {
         foreach ($to as $item) {
             $mailer->addAddress($item);
         }
     } else {
         $mailer->addAddress($to);
     }
     return $mailer->send();
 }
 public function mail()
 {
     // FOR WINDOWS
     //require_once("C:\\xampp\PHPMailer\PHPMailerAutoload.php");
     // FOR LINUX
     require_once "/usr/share/php/PHPMailer/PHPMailerAutoload.php";
     $cred = $this->bulletin_model->getEmailCredentials('dewslmonitoring');
     $mail = new PHPMailer();
     $mail->SMTPOptions = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true));
     $mail->SMTPDebug = 0;
     $mail->isSMTP();
     // Set mailer to use SMTP
     $mail->Host = 'smtp.gmail.com';
     // Specify main and backup SMTP servers
     $mail->SMTPAuth = true;
     $mail->Username = $cred['email'];
     $mail->Password = $cred['password'];
     $mail->SMTPSecure = 'ssl';
     $mail->Port = 465;
     $mail->setFrom($cred['email'], 'DEWS-L Monitoring');
     $mail->addAddress('*****@*****.**');
     $mail->addAddress('*****@*****.**');
     $mail->addAddress('*****@*****.**');
     $mail->addReplyTo($cred['email'], 'DEWS-L Monitoring');
     $mail->addCustomHeader('In-Reply-To', '<' . $cred['email'] . '>');
     $mail->isHTML(true);
     $mail->Subject = $_POST['subject'];
     $mail->Body = $_POST['text'];
     //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
     $file = $_SERVER['DOCUMENT_ROOT'] . "/bulletin.pdf";
     $mail->addAttachment($file, $_POST['filename'], 'base64', 'application/pdf');
     if (!$mail->send()) {
         echo 'Message could not be sent.';
         echo 'Mailer Error: ' . $mail->ErrorInfo;
     } else {
         echo 'Sent.';
     }
 }
     if (wp_mail($mail_recipient, $customSubject, $message, $headers)) {
         $submit_ok++;
         $partial_submit_ok++;
         $error_info[] = 'submit ok [wp_mail()]';
         $status_submit = 1;
     } else {
         $submit_error++;
         $partial_submit_error++;
         $error_info[] = 'wp_mail() error';
         $status_submit = 2;
     }
 } else {
     //pro
     if (isset($knewsOptions['bounce_on']) && $knewsOptions['bounce_on'] == '1') {
         if ($this->im_networked()) {
             $mail->addCustomHeader("Knews-Blog-Id: " . get_current_blog_id() . ' _');
         } else {
             $mail->addCustomHeader("Knews-Blog-Id: " . $this->KNEWS_MAIN_BLOG_ID . ' _');
         }
         if ($idNewsletter != 0) {
             $mail->addCustomHeader("Knews-News-Id: " . $idNewsletter . ' _');
         }
     }
     //fi pro
     $mail->Subject = $customSubject;
     if (strpos($recipient->email, '@knewstest.com') === false) {
         $mail_recipient = $recipient->email;
     } else {
         $mail_recipient = get_option('admin_email');
     }
     $mail->AddAddress($mail_recipient);
/**
 * Send Email:
 * Looks for pending threads, sends to memebers if member has sent email
 *
 * @throws Exception
 * @throws phpmailerException
 */
function wpmg_cron_send_email()
{
    //To debug, adjust settings here.
    $args = array('post_type' => 'mg_threads', 'post_status' => 'draft', 'perm' => 'readable', 'meta_key' => 'mg_thread_email_status', 'meta_value' => 'Pending');
    //All pending emails
    $query = new WP_Query($args);
    $threads = $query->get_posts();
    if (count($threads) > 0) {
        foreach ($threads as $emailParsed) {
            //Single Thread Information generated
            $thread_id = $emailParsed->ID;
            $group_id = get_post_meta($thread_id, 'mg_thread_email_group_id', true);
            $senderEmail = get_post_meta($thread_id, 'mg_thread_email_from', true);
            $is_active_group = get_post_meta($group_id, 'mg_group_status', true);
            $thread_subject = get_post_meta($thread_id, 'mg_thread_email_subject', true);
            //Filter Out specific automated emails
            $test_out_office = "/out of the office/i";
            if (preg_match($test_out_office, $thread_subject)) {
                update_post_meta($thread_id, 'mg_thread_email_status', 'Out of Office');
                break;
            }
            $test_auto = "/automatic reply/i";
            if (preg_match($test_auto, $thread_subject)) {
                update_post_meta($thread_id, 'mg_thread_email_status', 'Automatic Reply');
                break;
            }
            //Checks to see if group is active and valid
            if ($is_active_group == 2 && is_numeric($group_id) && $group_id > 0) {
                /* get sender user details */
                $senderUser = get_user_by("email", $senderEmail);
                $senderUserId = $senderUser->ID;
                $senderEmail = $senderUser->user_email;
                //Checks if user is valid
                if (is_numeric($senderUserId)) {
                    /* get other users from the sender user group */
                    $args = array('meta_query' => array('relation' => 'AND', array('key' => 'mg_user_group_sub_arr', 'value' => '"' . $group_id . '"', 'compare' => 'LIKE'), array('key' => 'mg_user_status', 'value' => 1)));
                    $user_query = new WP_User_Query($args);
                    //Checks to see if sender is in group
                    $in_group = false;
                    foreach ($user_query->get_results() as $memberstoSent) {
                        if ($senderUserId == $memberstoSent->ID) {
                            $in_group = true;
                            break;
                        } else {
                            $in_group = false;
                        }
                    }
                    if ($user_query->get_total() > 0 && $in_group == true) {
                        //Get group information to build email
                        $groupTitle = get_the_title($group_id);
                        $groupEmail = get_post_meta($group_id, 'mg_group_email', true);
                        $mail_type = get_post_meta($group_id, 'mg_group_mail_type', true);
                        //Email information
                        $has_parent = get_post_meta($thread_id, 'mg_thread_parent_id', true);
                        $body = get_post_meta($thread_id, 'mg_thread_email_content', true);
                        //Generates footer for email from group listing
                        $footerText = nl2br(stripslashes(get_post_meta($group_id, 'mg_group_footer_text', true)));
                        if (empty($has_parent)) {
                            $footerText = str_replace("{%grouptitle%}", $groupTitle, $footerText);
                            $footerText = str_replace("{%site_url%}", get_site_url(), $footerText);
                            $footerText = str_replace("{%archive_url%}", get_permalink($group_id), $footerText);
                            $footerText = str_replace("{%profile_url%}", get_admin_url("", "profile.php"), $footerText);
                            //Needs development to add unsusbscribe to footer
                            //							$footerText = str_replace( "{%unsubscribe_url%}", get_bloginfo( 'wpurl' ) . '?unsubscribe=1&userid=' . $sendtouserId . '&group=' . $group_id, $footerText );
                            $body .= $footerText;
                        }
                        if ($mail_type == 'smtp') {
                            global $phpmailer;
                            if (!is_object($phpmailer) || !is_a($phpmailer, 'PHPMailer')) {
                                require_once ABSPATH . WPINC . '/class-phpmailer.php';
                                require_once ABSPATH . WPINC . '/class-smtp.php';
                                $phpmailer = new PHPMailer();
                            }
                            $mail = new PHPMailer();
                            $mail->IsSMTP();
                            $mail->SMTPDebug = 0;
                            /*
                             * Connect to SMTP
                             */
                            //Add Thread ID to references, if replied to, becomes parent of reply
                            if (get_post_meta($group_id, 'mg_group_smtp_username', true) != '' && get_post_meta($group_id, 'mg_group_smtp_password', true) != '') {
                                $mail->Username = get_post_meta($group_id, 'mg_group_smtp_username', true);
                                $mail->Password = get_post_meta($group_id, 'mg_group_smtp_password', true);
                                $mail->SMTPAuth = true;
                                $mail->SMTPSecure = "ssl";
                            } else {
                                $mail->Username = $groupEmail;
                                $mail->Password = get_post_meta($group_id, 'mg_group_password', true);
                                $mail->SMTPAuth = false;
                            }
                            $mail->Host = get_post_meta($group_id, 'mg_group_smtp_server', true);
                            $mail->Port = get_post_meta($group_id, 'mg_group_smtp_port', true);
                            /* Custom Headers
                            
                            							$mail->addCustomHeader( 'Errors-To', 'no-reply@domain' );
                            							$mail->addCustomHeader( 'Return-Path', 'no-reply-bounces@domain' );
                            							*/
                            $mail->addCustomHeader('references', '[' . $thread_id . ']');
                            $mail->addCustomHeader('sender', $groupEmail);
                            //Set top level addresses
                            $mail->SetFrom($senderEmail);
                            $mail->AddReplyTo($groupEmail, $groupTitle);
                            $mail->AddAddress($groupEmail, $groupTitle);
                            //Add each user in group to bcc email
                            foreach ($user_query->get_results() as $memberstoSent) {
                                $sendtouserId = $memberstoSent->ID;
                                $Userrow = get_user_by("id", $sendtouserId);
                                $sendToEmail = $Userrow->user_email;
                                $mail->addBCC($sendToEmail);
                            }
                            //Subject fron thread
                            $mail->Subject = get_post_meta($thread_id, 'mg_thread_email_subject', true);
                            //Email formating for body
                            //							$mail->IsHTML( true );
                            $mail->MsgHTML($body);
                            $mail->CharSet = 'utf-8';
                            //							$mail->Body = $body;
                            $alt_body = nl2br($mail->html2text($body));
                            $mail->AltBody = $alt_body;
                            //Add attachments to email from thread
                            $args = array('numberposts' => -1, 'post_parent' => $thread_id, 'post_status' => null, 'post_type' => 'attachment');
                            $attachments = get_children($args);
                            if ($attachments) {
                                foreach ($attachments as $attachment) {
                                    if (get_post_meta($attachment->ID, '_wp_attachment_image_alt', true) == 'ATTACHMENT') {
                                        $fullsize_path = get_attached_file($attachment->ID);
                                        $filename_only = basename($fullsize_path);
                                        //If is attached .eml(needs 8bit encoding)
                                        if ($attachment->post_mime_type == 'message/rfc822') {
                                            $mail->addAttachment($fullsize_path, $filename_only, '8bit');
                                        } else {
                                            $mail->addAttachment($fullsize_path, $filename_only);
                                        }
                                    }
                                }
                            }
                            //If email is sent, update status and post
                            if ($mail->Send()) {
                                update_post_meta($thread_id, 'mg_thread_email_status', 'Sent');
                                $thread_update = array('ID' => $thread_id, 'post_status' => 'publish');
                                wp_update_post($thread_update);
                            } else {
                                update_post_meta($thread_id, 'mg_thread_email_status', 'Error');
                                update_post_meta($thread_id, 'mg_thread_email_status_error', $mail->ErrorInfo);
                            }
                        }
                        //Needs to be updated to SMTP format
                        if ($mail_type == 'php') {
                            $mail_Subject = get_post_meta($thread_id, 'mg_thread_email_subject', true);
                            $to = array();
                            foreach ($user_query->get_results() as $memberstoSent) {
                                $sendtouserId = $memberstoSent->ID;
                                $Userrow = get_user_by("id", $sendtouserId);
                                $sendToEmail = $Userrow->user_email;
                                $to[] = $sendToEmail;
                            }
                            $subject = $mail_Subject;
                            $headers = 'From: ' . $groupTitle . '<' . $groupEmail . '>' . "\r\n";
                            $headers .= 'Reply-To: <' . $senderEmail . '>' . "\r\n";
                            $headers .= 'X-Mailer: PHP' . phpversion() . "\r\n";
                            $headers .= 'MIME-Version: 1.0' . "\r\n";
                            $headers .= 'Content-Type: ' . get_bloginfo('html_type') . '; charset=\\"' . get_bloginfo('charset') . '\\"' . "\r\n";
                            $headers .= 'references: [' . $thread_id . ']' . "\r\n";
                            $headers .= 'Content-type: text/html' . "\r\n";
                            $php_sent = mail($to, $subject, $body, $headers);
                            if ($php_sent) {
                                update_post_meta($thread_id, 'mg_thread_email_status', 'Sent');
                                $thread_update = array('ID' => $thread_id, 'post_status' => 'publish');
                                wp_update_post($thread_update);
                            } else {
                                update_post_meta($thread_id, 'mg_thread_email_status', 'Error');
                            }
                        }
                        //Needs to be updated to SMTP format
                        if ($mail_type == 'wp') {
                            $mail_Subject = get_post_meta($thread_id, 'mg_thread_email_subject', true);
                            $to = array();
                            foreach ($user_query->get_results() as $memberstoSent) {
                                $sendtouserId = $memberstoSent->ID;
                                $Userrow = get_user_by("id", $sendtouserId);
                                $sendToEmail = $Userrow->user_email;
                                $to[] = $sendToEmail;
                            }
                            $subject = $mail_Subject;
                            $headers[] = 'From: ' . $groupTitle . '<' . $groupEmail . '>' . "\r\n";
                            $headers[] = 'Reply-To: <' . $senderEmail . '>' . "\r\n";
                            /* $headers[] = 'Cc: '. $sendToName .'<'.$sendToEmail.'>'."\r\n"; */
                            $headers[] = 'X-Mailer: PHP' . phpversion() . "\r\n";
                            $headers[] = 'MIME-Version: 1.0' . "\r\n";
                            $headers[] = 'Content-Type: ' . get_bloginfo('html_type') . '; charset=\\"' . get_bloginfo('charset') . '\\"' . "\r\n";
                            $headers[] = 'Content-type: text/html' . "\r\n";
                            $args = array('numberposts' => -1, 'post_parent' => $thread_id, 'post_status' => null, 'post_type' => 'attachment');
                            $attachments = get_children($args);
                            $attachment_send = array();
                            foreach ($attachments as $attachment) {
                                if (get_post_meta($attachment->ID, '_wp_attachment_image_alt', true) === 'ATTACHMENT') {
                                    $fullsize_path = get_attached_file($attachment->ID);
                                    $attachment_send[] = $fullsize_path;
                                }
                            }
                            $wp_sent = wp_mail($to, $subject, $body, $headers, $attachment_send);
                            if ($wp_sent) {
                                update_post_meta($thread_id, 'mg_thread_email_status', 'Sent');
                                $thread_update = array('ID' => $thread_id, 'post_status' => 'publish');
                                wp_update_post($thread_update);
                            } else {
                                update_post_meta($thread_id, 'mg_thread_email_status', 'Error');
                            }
                        }
                    } else {
                        echo "No other user subscribed in this group!";
                    }
                } else {
                    echo "No Valid Sender Found in DB!";
                }
            } else {
                echo "No Valid Mailing Group Found!";
            }
        }
    } else {
        echo "No Parsed Email found!";
    }
}
Example #24
0
 public function send_email_campaign($sender_data, $receiver_data, $template_data, $user_config)
 {
     $this->load->library('My_PHPMailer');
     $setup = array("smtp_host" => $user_config['smtp_host'], "smtp_port" => $user_config['smtp_port'], "smtp_protocol" => "TLS", "smtp_auth" => true, "smtp_username" => $user_config['smtp_username'], "smtp_password" => $user_config['smtp_password']);
     $mail = new PHPMailer();
     $mail->XMailer = 'PHP ';
     $mail->CharSet = 'UTF-8';
     //$mail->SMTPDebug = 3; // Enable verbose debug output
     $mail->isSMTP();
     // Set mailer to use SMTP
     $mail->Host = $setup['smtp_host'];
     // Specify main and backup SMTP servers  'smtp1.example.com;smtp2.example.com'
     $mail->SMTPAuth = $setup['smtp_auth'] ? true : false;
     // Enable SMTP authentication
     $mail->Username = $setup['smtp_username'];
     // SMTP username
     $mail->Password = $setup['smtp_password'];
     // SMTP password
     $mail->SMTPSecure = $setup['smtp_protocol'];
     // Enable TLS encryption, `ssl` also accepted
     $mail->Port = $setup['smtp_port'];
     // TCP port to connect to
     $mail->ClearAllRecipients();
     $mail->ClearAddresses();
     $mail->ClearCCs();
     $mail->ClearBCCs();
     $mail->ClearReplyTos();
     $mail->ClearAttachments();
     $mail->ClearCustomHeaders();
     $mail->From = $sender_data['email'];
     $mail->FromName = $sender_data['name'];
     $mail->addAddress($receiver_data['email'], $receiver_data['name']);
     // Add a recipient
     $mail->addReplyTo($sender_data['email'], '');
     $mail->isHTML(true);
     // Set email format to HTML
     $body = $this->load->view('email/campaign_email', array('template_data' => $template_data), true);
     $mail->Subject = $template_data['subject'];
     $mail->Body = $body;
     // html mail
     $mail->AltBody = $body;
     // Plain text mail
     // For most clients expecting the Priority header:
     // 1 = High, 2 = Medium, 3 = Low
     $mail->Priority = 1;
     // MS Outlook custom header
     // May set to "Urgent" or "Highest" rather than "High"
     $mail->AddCustomHeader("X-MSMail-Priority: High");
     // Not sure if Priority will also set the Importance header:
     $mail->AddCustomHeader("Importance: High");
     $mail->AddCustomHeader("X-Sender: <{''}>\n");
     $mail->addCustomHeader("List-Unsubscribe", "<mailto:unsubscribe@digibuzz24.net/unsubscribe.php?email='" . $sender_data['email'] . "'>");
     $mail->addCustomHeader("List-Subscribe", "<mailto:subscribe@digibuzz24.net/subscribe.php?email='" . $sender_data['email'] . "'>");
     $mail->addCustomHeader("List-Owner", "<mailto:admin@digibuzz24.net>");
     // Uncomment this
     if ($mail->send()) {
         return 'ok';
     } else {
         //echo 'Mailer Error: ' . $mail->ErrorInfo; exit;
         return 'error';
     }
 }
Example #25
0
 function smtpSend()
 {
     $mail = new PHPMailer(true);
     $mail->IsSMTP();
     $mail->SMTPAuth = true;
     $mail->Host = SMTP_HOST;
     $mail->Port = SMTP_PORT;
     $mail->Username = SMTP_USERNAME;
     $mail->Password = SMTP_PASSWORD;
     $mail->Subject = $this->_subject;
     $mail->SetFrom($this->_from['email_address'], $this->_from['name']);
     $mail->CharSet = $this->_charset;
     $mail->Encoding = $this->_content_transfer_encoding;
     if (empty($this->_body_plain)) {
         $mail->MsgHTML($this->_body_html);
     } else {
         $mail->AltBody = $this->_body_plain;
     }
     foreach ($this->_headers as $key => $value) {
         $mail->addCustomHeader($key, $value);
     }
     if (!empty($this->_to)) {
         foreach ($this->_to as $to) {
             $mail->AddAddress($to['email_address'], $to['name']);
         }
     }
     if (!empty($this->_cc)) {
         foreach ($this->_cc as $cc) {
             $mail->AddCC($cc['email_address'], $cc['name']);
         }
     }
     if (!empty($this->_bcc)) {
         foreach ($this->_bcc as $bcc) {
             $mail->AddBCC($bcc['email_address'], $bcc['name']);
         }
     }
     if (!empty($this->_attachments)) {
         foreach ($this->_attachments as $attachment) {
             $mail->AddAttachment($attachment['file'], $attachment['filename']);
         }
     }
     if (!empty($this->_images)) {
         foreach ($this->_images as $image) {
             $mail->AddEmbeddedImage($image['file'], $image['filename']);
         }
     }
     try {
         $mail->Send();
     } catch (Exception $e) {
         return false;
     }
     return true;
 }
Example #26
0
 /**
  * Set 'Reply-To' email address for PHPMailer if mailbox is > 64 characters.
  *
  * Have to workaround a PHPMailer mailbox character limit issue by setting the
  * 'Reply-To' email address again after PHPMailer has done its checks.
  *
  * This is done for installs still using wp_mail().
  *
  * @since 1.0-RC4.
  * @link  https://github.com/PHPMailer/PHPMailer/issues/706
  *
  * @param PHPMailer $phpmailer
  */
 public function phpmailer_set_reply_to_header($phpmailer)
 {
     /*
      * Do a check to see if the reply-to email address is > 64 characters.
      *
      * If so, set the 'Reply-To' email address again since PHPMailer silently
      * drops our first attempt at doing this.
      */
     $reply_to = $this->get_reply_to_address($this->temp_args);
     if (strpos($reply_to, '@') > 64) {
         $phpmailer->addCustomHeader('Reply-To', $reply_to);
     }
     // Unset some temporary items.
     unset($this->temp_args);
     remove_action('phpmailer_init', array($this, 'phpmailer_set_reply_to_header'));
 }
Example #27
0
    foreach ($headers as $header => $value) {
        echo $header . ": " . $value . "\n";
    }
}
echo "Subject: " . $subject . "\n";
echo "From: " . $from . "\n";
echo "Reply-to: " . $reply_to . "\n";
echo "To: " . $to . "\n";
echo "Date: " . $date . "\n";
//echo "Body: ".$body."\n";
//add to, from, fromname, custom headers and subject to the email
$mail->From = $smtp['from'];
$mail->FromName = $smtp['from_name'];
if (sizeof($headers) > 0) {
    foreach ($headers as $header => $value) {
        $mail->addCustomHeader($header . ": " . $value);
    }
}
$mail->Subject = $subject;
$to = trim($to, "<> ");
$to = str_replace(";", ",", $to);
$to_array = explode(",", $to);
if (count($to_array) == 0) {
    $mail->AddAddress($to);
} else {
    foreach ($to_array as $to_row) {
        if (strlen($to_row) > 0) {
            echo "Add Address: {$to_row}\n";
            $mail->AddAddress(trim($to_row));
        }
    }
Example #28
-1
/**
 * Send an email using phpmailer
 *
 * @param string $from       From address
 * @param string $from_name  From name
 * @param string $to         To address
 * @param string $to_name    To name
 * @param string $subject    The subject of the message.
 * @param string $body       The message body
 * @param array  $bcc        Array of address strings
 * @param bool   $html       Set true for html email, also consider setting
 *                           altbody in $params array
 * @param array  $files      Array of file descriptor arrays, each file array
 *                           consists of full path and name
 * @param array  $params     Additional parameters
 * @return bool
 */
function phpmailer_send_html($from, $from_name, $to, $to_name, $subject, $body, $headers = null)
{
    static $phpmailer;
    // Ensure phpmailer object exists
    if (!is_object($phpmailer) || !is_a($phpmailer, 'PHPMailer')) {
        require_once elgg_get_plugins_path() . '/phpmailer/vendors/class.phpmailer.php';
        require_once elgg_get_plugins_path() . '/phpmailer/vendors/class.smtp.php';
        $phpmailer = new PHPMailer();
    }
    if (!$from) {
        throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'from'));
    }
    if (!$to && !$bcc) {
        throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'to'));
    }
    if (!$subject) {
        throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'subject'));
    }
    // set line ending if admin selected \n (if admin did not change setting, null is returned)
    if (elgg_get_plugin_setting('nonstd_mta', 'phpmailer')) {
        $phpmailer->LE = "\n";
    } else {
        $phpmailer->LE = "\r\n";
    }
    ////////////////////////////////////
    // Format message
    $phpmailer->ClearAllRecipients();
    $phpmailer->ClearAttachments();
    // Set the from name and email
    $phpmailer->From = $from;
    $phpmailer->FromName = $from_name;
    // Set destination address
    if (isset($to)) {
        $phpmailer->AddAddress($to, $to_name);
    }
    // set bccs if exists
    if ($bcc && is_array($bcc)) {
        foreach ($bcc as $address) {
            $phpmailer->AddBCC($address);
        }
    }
    $phpmailer->Subject = $subject;
    $phpmailer->IsHTML(true);
    $phpmailer->Body = $body;
    if ($files && is_array($files)) {
        foreach ($files as $file) {
            if (isset($file['path'])) {
                $phpmailer->AddAttachment($file['path'], $file['name']);
            }
        }
    }
    $is_smtp = elgg_get_plugin_setting('phpmailer_smtp', 'phpmailer');
    $smtp_host = elgg_get_plugin_setting('phpmailer_host', 'phpmailer');
    $smtp_auth = elgg_get_plugin_setting('phpmailer_smtp_auth', 'phpmailer');
    $is_ssl = elgg_get_plugin_setting('ep_phpmailer_ssl', 'phpmailer');
    $ssl_port = elgg_get_plugin_setting('ep_phpmailer_port', 'phpmailer');
    if ($is_smtp && isset($smtp_host)) {
        $phpmailer->IsSMTP();
        $phpmailer->Host = $smtp_host;
        $phpmailer->SMTPAuth = false;
        if ($smtp_auth) {
            $phpmailer->SMTPAuth = true;
            $phpmailer->Username = elgg_get_plugin_setting('phpmailer_username', 'phpmailer');
            $phpmailer->Password = elgg_get_plugin_setting('phpmailer_password', 'phpmailer');
            if ($is_ssl) {
                $phpmailer->SMTPSecure = "ssl";
                $phpmailer->Port = $ssl_port;
            }
        }
    } else {
        // use php's mail
        $phpmailer->IsMail();
    }
    $phpmailer->addCustomHeader($headers);
    $return = $phpmailer->Send();
    if (!$return) {
        elgg_log('PHPMailer error: ' . $phpmailer->ErrorInfo, 'WARNING');
    }
    return $return;
}
Example #29
-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;
}
Example #30
-4
 /**
  * Send a prepared and rendered email locally.
  *
  * @param array $email
  * @return bool
  */
 protected function send_prepared(array $email)
 {
     if (!is_email($email['to_address'])) {
         Prompt_Logging::add_error(Prompt_Enum_Error_Codes::OUTBOUND, __('Attempted to send to an invalid email address.', 'Postmatic'), compact('email'));
         return false;
     }
     $this->local_mailer->clearAllRecipients();
     $this->local_mailer->clearCustomHeaders();
     $this->local_mailer->clearReplyTos();
     $this->local_mailer->From = $email['from_address'];
     $this->local_mailer->FromName = $email['from_name'];
     $this->local_mailer->addAddress($email['to_address'], $email['to_name']);
     if (!empty($email['reply_address'])) {
         $this->local_mailer->addReplyTo($email['reply_address'], $email['reply_name']);
     }
     $unsubscribe_types = array(Prompt_Enum_Message_Types::COMMENT, Prompt_Enum_Message_Types::POST);
     if (!empty($email['reply_address']) and in_array($email['message_type'], $unsubscribe_types)) {
         $this->local_mailer->addCustomHeader('List-Unsubscribe', '<mailto:' . $email['reply_address'] . '?body=unsubscribe>');
     }
     $this->local_mailer->Subject = $email['subject'];
     $this->local_mailer->Body = $email['html_content'];
     $this->local_mailer->AltBody = $email['text_content'];
     $this->local_mailer->ContentType = Prompt_Enum_Content_Types::HTML;
     $this->local_mailer->isMail();
     $this->local_mailer->CharSet = 'UTF-8';
     try {
         $this->local_mailer->send();
     } catch (phpmailerException $e) {
         Prompt_Logging::add_error('prompt_wp_mail', __('Failed sending an email locally. Did you know Postmatic can deliver email for you?', 'Prompt_Core'), array('email' => $email, 'error_info' => $this->local_mailer->ErrorInfo));
         return false;
     }
     return true;
 }