Ejemplo n.º 1
0
 /**
  * Send email using swift api.
  * 
  * @param $body
  * @param $recipients
  * @param $from
  * @param $subject
  */
 public function sendEmail($body, $recipients, $from, $subject)
 {
     $config = Zend_Registry::get('config');
     $failures = '';
     Swift_Preferences::getInstance()->setCharset('UTF-8');
     //Create the Transport
     $transport = Swift_SmtpTransport::newInstance($config->mail->server->name, $config->mail->server->port, $config->mail->server->security)->setUsername($config->mail->username)->setPassword($config->mail->password);
     $mailer = Swift_Mailer::newInstance($transport);
     $message = Swift_Message::newInstance();
     $headers = $message->getHeaders();
     $headers->addTextHeader("signed-by", Constant::EMAIL_DOMAIN);
     //Give the message a subject
     $message->setSubject($subject);
     //Set the From address with an associative array
     $message->setFrom($from);
     //Set the To addresses with an associative array
     $message->setTo($recipients);
     //Give it a body
     $message->setBody($body);
     $message->setContentType("text/html");
     //Send the message
     $myresult = $mailer->batchSend($message);
     if ($myresult) {
         return null;
     } else {
         return Constant::EMAIL_FAIL_MESSAGE;
     }
 }
Ejemplo n.º 2
0
 public function setUp()
 {
     $this->_attFileName = 'data.txt';
     $this->_attFileType = 'text/plain';
     $this->_attFile = __DIR__ . '/../../_samples/files/data.txt';
     Swift_Preferences::getInstance()->setCharset('utf-8');
 }
Ejemplo n.º 3
0
 /**
  * Gets the instance of Preferences.
  *
  * @return Swift_Preferences
  */
 public static function getInstance()
 {
     if (!isset(self::$_instance)) {
         self::$_instance = new self();
     }
     return self::$_instance;
 }
 public function testDotStuffingEncodingAndDecodingSamplesFromDiConfiguredInstance()
 {
     // Enable DotEscaping
     Swift_Preferences::getInstance()->setQPDotEscape(true);
     $this->testEncodingAndDecodingSamplesFromDiConfiguredInstance();
     // Disable DotStuffing to continue
     Swift_Preferences::getInstance()->setQPDotEscape(false);
 }
Ejemplo n.º 5
0
 /**
  *
  * @param \Swift_Transport $transport
  */
 public function __construct(\Zend_Config $webconfig)
 {
     $this->setWebconfig($webconfig);
     if (null === $transport) {
         $transport = $this->createTransport();
     }
     parent::__construct($transport);
     \Swift_Preferences::getInstance()->setCharset('iso-8859-1');
 }
Ejemplo n.º 6
0
 public function sendHtmlMail($from, $to, $subject, $body, $attachments = array())
 {
     spl_autoload_unregister(array('YiiBase', 'autoload'));
     Yii::import('application.extensions.swift.swift_required', true);
     spl_autoload_register(array('YiiBase', 'autoload'));
     Swift_Preferences::getInstance()->setCharset('utf-8');
     $message = Swift_Message::newInstance()->setSubject($subject)->setFrom($from)->setTo($to)->setBody($body, 'text/html');
     $transport = Swift_MailTransport::newInstance();
     $mailer = Swift_Mailer::newInstance($transport);
     return $mailer->batchSend($message);
 }
Ejemplo n.º 7
0
 /**
  * Swift初期化
  *
  * @param String $host
  * @param String $port
  * @param String $user
  * @param String $pass
  * @param String $charset
  * @return vold
  * @codeCoverageIgnore
  */
 public function __construct($host, $port, $user, $pass, $charset = 'iso-2022-jp')
 {
     $this->host = $host;
     $this->port = $port;
     $this->user = $user;
     $this->pass = $pass;
     $this->charset = $charset;
     $this->setPath();
     \Swift::init(function () use($charset) {
         \Swift_DependencyContainer::getInstance()->register('mime.qpheaderencoder')->asAliasOf('mime.base64headerencoder');
         \Swift_Preferences::getInstance()->setCharset($charset);
     });
 }
Ejemplo n.º 8
0
 protected function _preferences()
 {
     // Sets the default charset so that setCharset() is not needed elsewhere
     \Swift_Preferences::getInstance()->setCharset('utf-8');
     // Without these lines the default caching mechanism is "array" but this uses a lot of memory
     // If possible, use a disk cache to enable attaching large attachments etc.
     // You can override the default temporary directory by setting the TMPDIR environment variable.
     //        if (function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir())) {
     //            \Swift_Preferences::getInstance()
     //                    ->setTempDir(sys_get_temp_dir())
     //                    ->setCacheType('disk');
     //        }
     \Swift_Preferences::getInstance()->setTempDir(self::getPathTmp())->setCacheType('disk');
     \Swift_Preferences::getInstance()->setQPDotEscape(false);
 }
Ejemplo n.º 9
0
 /**
  * Load our Email setting from `app/config/email.php` over riding any values set in `app/config/dev.email.php` if the 
  * application is in `DEV_MODE`. 
  *
  *
  * @return void
  */
 public function __construct()
 {
     if (is_file(\App::path() . '/app/config/email.php')) {
         $this->settings = (require \App::path() . '/app/config/email.php');
     }
     //if
     if (\App::devMode()) {
         $devSettings = \App::path() . '/app/config/dev.email.php';
         if (is_file($devSettings)) {
             $this->settings = array_merge($this->settings, require $devSettings);
         }
         //if
     }
     //if
     $charset = $this->getSetting('CHARSET');
     if (!$charset) {
         $charset = 'iso-8859-2';
     }
     //if
     \Swift_Preferences::getInstance()->setCharset($charset);
 }
Ejemplo n.º 10
0
function swiftmailer_configurator()
{
    Swift_Preferences::getInstance()->setCharset(JsonApiApplication::$charset);
}
Ejemplo n.º 11
0
function mf_send_resume_link($dbh, $form_name, $form_resume_url, $resume_email)
{
    global $mf_lang;
    //get settings first
    $mf_settings = mf_get_settings($dbh);
    $subject = sprintf($mf_lang['resume_email_subject'], $form_name);
    $email_content = sprintf($mf_lang['resume_email_content'], $form_name, $form_resume_url, $form_resume_url);
    $subject = utf8_encode($subject);
    //create the mail transport
    if (!empty($mf_settings['smtp_enable'])) {
        $s_transport = Swift_SmtpTransport::newInstance($mf_settings['smtp_host'], $mf_settings['smtp_port']);
        if (!empty($mf_settings['smtp_secure'])) {
            $s_transport->setEncryption('tls');
        }
        if (!empty($mf_settings['smtp_auth'])) {
            $s_transport->setUsername($mf_settings['smtp_username']);
            $s_transport->setPassword($mf_settings['smtp_password']);
        }
    } else {
        $s_transport = Swift_MailTransport::newInstance();
        //use PHP mail() transport
    }
    //create mailer instance
    $s_mailer = Swift_Mailer::newInstance($s_transport);
    if (file_exists($mf_settings['upload_dir'] . "/form_{$form_id}/files")) {
        Swift_Preferences::getInstance()->setCacheType('disk')->setTempDir($mf_settings['upload_dir'] . "/form_{$form_id}/files");
    }
    $from_name = html_entity_decode($mf_settings['default_from_name'], ENT_QUOTES);
    $from_email = $mf_settings['default_from_email'];
    if (!empty($resume_email) && !empty($form_resume_url)) {
        $s_message = Swift_Message::newInstance()->setCharset('utf-8')->setMaxLineLength(1000)->setSubject($subject)->setFrom(array($from_email => $from_name))->setSender($from_email)->setReturnPath($from_email)->setTo($resume_email)->setBody($email_content, 'text/html');
        //send the message
        $send_result = $s_mailer->send($s_message);
        if (empty($send_result)) {
            echo "Error sending email!";
        }
    }
}
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run_archive(&$job_object)
 {
     $job_object->substeps_todo = 1;
     $job_object->log(sprintf(__('%d. Try to send backup with email …', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     //check file Size
     if (!empty($job_object->job['emailefilesize'])) {
         if ($job_object->backup_filesize > $job_object->job['emailefilesize'] * 1024 * 1024) {
             $job_object->log(__('Backup archive too big to be sent by email!', 'backwpup'), E_USER_ERROR);
             $job_object->substeps_done = 1;
             return TRUE;
         }
     }
     $job_object->log(sprintf(__('Sending email to %s…', 'backwpup'), $job_object->job['emailaddress']), E_USER_NOTICE);
     //get mail settings
     $emailmethod = 'mail';
     $emailsendmail = '';
     $emailhost = '';
     $emailhostport = '';
     $emailsecure = '';
     $emailuser = '';
     $emailpass = '';
     if (empty($job_object->job['emailmethod'])) {
         //do so if i'm the wp_mail to get the settings
         global $phpmailer;
         // (Re)create it, if it's gone missing
         if (!is_object($phpmailer) || !$phpmailer instanceof PHPMailer) {
             require_once ABSPATH . WPINC . '/class-phpmailer.php';
             require_once ABSPATH . WPINC . '/class-smtp.php';
             $phpmailer = new PHPMailer(true);
         }
         //only if PHPMailer really used
         if (is_object($phpmailer)) {
             do_action_ref_array('phpmailer_init', array(&$phpmailer));
             //get settings from PHPMailer
             $emailmethod = $phpmailer->Mailer;
             $emailsendmail = $phpmailer->Sendmail;
             $emailhost = $phpmailer->Host;
             $emailhostport = $phpmailer->Port;
             $emailsecure = $phpmailer->SMTPSecure;
             $emailuser = $phpmailer->Username;
             $emailpass = $phpmailer->Password;
         }
     } else {
         $emailmethod = $job_object->job['emailmethod'];
         $emailsendmail = $job_object->job['emailsendmail'];
         $emailhost = $job_object->job['emailhost'];
         $emailhostport = $job_object->job['emailhostport'];
         $emailsecure = $job_object->job['emailsecure'];
         $emailuser = $job_object->job['emailuser'];
         $emailpass = BackWPup_Encryption::decrypt($job_object->job['emailpass']);
     }
     //Generate mail with Swift Mailer
     if (function_exists('mb_internal_encoding') && (int) ini_get('mbstring.func_overload') & 2) {
         $mbEncoding = mb_internal_encoding();
         mb_internal_encoding('ASCII');
     }
     try {
         //Set Temp dir for mailing
         Swift_Preferences::getInstance()->setTempDir(untrailingslashit(BackWPup::get_plugin_data('TEMP')))->setCacheType('disk');
         // Create the Transport
         if ($emailmethod == 'smtp') {
             $transport = Swift_SmtpTransport::newInstance($emailhost, $emailhostport);
             $transport->setUsername($emailuser);
             $transport->setPassword($emailpass);
             if ($emailsecure == 'ssl') {
                 $transport->setEncryption('ssl');
             }
             if ($emailsecure == 'tls') {
                 $transport->setEncryption('tls');
             }
         } elseif ($emailmethod == 'sendmail') {
             $transport = Swift_SendmailTransport::newInstance($emailsendmail);
         } else {
             $job_object->need_free_memory($job_object->backup_filesize * 8);
             $transport = Swift_MailTransport::newInstance();
         }
         // Create the Mailer using your created Transport
         $emailer = Swift_Mailer::newInstance($transport);
         // Create a message
         $message = Swift_Message::newInstance(sprintf(__('BackWPup archive from %1$s: %2$s', 'backwpup'), date_i18n('d-M-Y H:i', $job_object->start_time, TRUE), esc_attr($job_object->job['name'])));
         $message->setFrom(array($job_object->job['emailsndemail'] => $job_object->job['emailsndemailname']));
         $message->setTo(array($job_object->job['emailaddress']));
         $message->setBody(sprintf(__('Backup archive: %s', 'backwpup'), $job_object->backup_file), 'text/plain', strtolower(get_bloginfo('charset')));
         $message->attach(Swift_Attachment::fromPath($job_object->backup_folder . $job_object->backup_file, $job_object->get_mime_type($job_object->backup_folder . $job_object->backup_file)));
         // Send the message
         $result = $emailer->send($message);
     } catch (Exception $e) {
         $job_object->log('Swift Mailer: ' . $e->getMessage(), E_USER_ERROR);
     }
     if (isset($mbEncoding)) {
         mb_internal_encoding($mbEncoding);
     }
     if (isset($result) && !$result) {
         $job_object->log(__('Error while sending email!', 'backwpup'), E_USER_ERROR);
         return FALSE;
     } else {
         $job_object->substeps_done = 1;
         $job_object->log(__('Email sent.', 'backwpup'), E_USER_NOTICE);
         return TRUE;
     }
 }
Ejemplo n.º 13
0
 */
try {
    ClassLoader::scanAndRegister();
} catch (UnresolvableDependenciesException $e) {
    die($e->getMessage());
    // see #6343
}
/**
 * Include the Composer autoloader
 */
require_once TL_ROOT . '/vendor/autoload.php';
/**
 * Override some SwiftMailer defaults
 */
Swift::init(function () {
    $preferences = Swift_Preferences::getInstance();
    if (!Config::get('useFTP')) {
        $preferences->setTempDir(TL_ROOT . '/system/tmp')->setCacheType('disk');
    }
    $preferences->setCharset(Config::get('characterSet'));
});
/**
 * Define the relative path to the installation (see #5339)
 */
if (file_exists(TL_ROOT . '/system/config/pathconfig.php') && TL_SCRIPT != 'contao/install.php') {
    define('TL_PATH', include TL_ROOT . '/system/config/pathconfig.php');
} elseif (TL_MODE == 'BE') {
    define('TL_PATH', preg_replace('/\\/contao\\/[a-z]+\\.php$/i', '', Environment::get('scriptName')));
} else {
    define('TL_PATH', null);
    // cannot be reliably determined
 public function setUp()
 {
     Swift_Preferences::getInstance()->setCharset('utf-8');
 }
Ejemplo n.º 15
0
<?php

require __DIR__ . '/../vendor/autoload.php';
\Swift::init(function () {
    \Swift_DependencyContainer::getInstance()->register('mime.qpheaderencoder')->asAliasOf('mime.base64headerencoder');
    \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
});
$message = \Swift_Message::newInstance()->setSubject('件名')->setFrom(['*****@*****.**' => 'テスト送信者'])->setTo(['*****@*****.**'])->setBody("メール本文です\n1234567890\nあいうえおかきくけko\n")->setCharset('iso-2022-jp')->setEncoder(new \Swift_Mime_ContentEncoder_PlainContentEncoder('7bit'));
$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$mailer->send($message);
echo "sent\n";
Ejemplo n.º 16
0
function send_email($bcc_list, $subject, $bb_body, $reply_to = NULL, $prefix = NULL, $footer = NULL, $headers = NULL)
{
    global $EMAIL_ADDRESS, $EMAIL_USERNAME, $EMAIL_PASSWORD, $SMTP_SERVER, $SMTP_SERVER_PORT, $SMTP_SERVER_PROTOCOL, $LMT_EMAIL;
    require_once PATH::lib() . "/swiftmailer/swift_required.php";
    //Instead of using parameter default values, so we can pass NULL. And it's more readable.
    if (count($bcc_list) == 0) {
        return true;
    }
    if (is_null($reply_to)) {
        $reply_to = array($EMAIL_ADDRESS => 'LHS Math Club Mailbot');
    }
    if (is_null($prefix)) {
        $prefix = '[LHS Math Club]';
    }
    if (is_null($footer)) {
        $footer = "LHS Math Club\n[url]" . get_site_url() . "[/url]\nTo stop receiving LHSMATH emails, contact [email]webmaster@lhsmath.org[/email].";
    }
    if (is_null($headers)) {
        $headers = array();
    }
    if (is_string($bcc_list)) {
        $bcc_list = array($bcc_list);
    }
    if (!is_array($bcc_list) || !is_string($subject) || !is_string($bb_body) || !is_array($reply_to) && !is_string($reply_to) || !is_string($prefix) || !is_string($footer) || !is_array($headers)) {
        return 'Invalid email parameters.';
    }
    if (($error_msg = val_email_msg($subject, $bb_body)) !== true) {
        return $error_msg;
    }
    if ($footer != "") {
        $bb_body .= "\n\n\n---\n{$footer}\n";
    }
    //Attach footer.
    $html = BBCode($bb_body);
    //BBCode it.
    $subject = preg_replace("/[^\\S ]/ui", '', strip_tags($prefix . ' ' . $subject));
    //"remove everything that's not [non-whitespace or space]"
    //preg_replace("/[^[:alnum][:space]]/ui", '', $string);?
    //Ok everything seems to be working, let's go ahead
    Swift_Preferences::getInstance()->setCacheType('array');
    //Prevents a ton of warnings about SwiftMail's DiskKeyCache, thus actually speeding things up considerably.
    //Connect to the SMTP server
    $transport = Swift_SmtpTransport::newInstance($SMTP_SERVER, $SMTP_SERVER_PORT, $SMTP_SERVER_PROTOCOL)->setUsername($EMAIL_USERNAME)->setPassword($EMAIL_PASSWORD);
    //Make a Mailer that will send through that transport (limiting to 50/send)
    $mailer = Swift_Mailer::newInstance($transport);
    //$mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(50, 1));//Max 50 emails per send, 1 sec delay between sends
    try {
        //Mush all info into the Mailer
        $message = Swift_Message::newInstance($subject)->setFrom(array($EMAIL_ADDRESS => 'LHS Math Club Mailbot'))->setBcc($bcc_list)->setContentType("text/html")->setBody($html)->setReplyTo($reply_to);
        foreach ($headers as $field => $value) {
            //Add custom headers, such as listserv stuff.
            $message->getHeaders()->addTextHeader($field, $value);
        }
        //Send the message
        if (!$mailer->send($message)) {
            LOG::fatal('Error sending email');
        }
    } catch (Exception $e) {
        LOG::fatal('Email exception: ' . $e->getMessage());
    }
    return true;
}
Ejemplo n.º 17
0
 /**
  * Initialize a new Swift_Message, set the subject and body.
  *
  * @param   string  message subject
  * @param   string  message body
  * @param   string  body mime type
  * @return  void
  */
 public function __construct($subject = null, $message = null, $type = null)
 {
     \Swift::init(function () {
         // Set the default character set for everything
         \Swift_Preferences::getInstance()->setCharset('utf-8');
     });
     // Create a new message, match internal character set
     $this->swiftmessage = \Swift_Message::newInstance();
     if ($subject) {
         // Apply subject
         $this->subject($subject);
     }
     if ($message) {
         // Apply message, with type
         $this->message($message, $type);
     }
 }
Ejemplo n.º 18
0
<?php

Swift::init(function () {
    $charset = Kohana::$charset;
    // Set the default character set for everything
    Swift_Preferences::getInstance()->setCharset($charset);
});
Ejemplo n.º 19
0
 /**
  * Class constructor
  */
 public function __construct(iPhorm $form)
 {
     parent::__construct($form);
     Swift_Preferences::setCharset($form->getCharset());
 }
Ejemplo n.º 20
0
 /**
  * sends test mail
  */
 public function edit_ajax()
 {
     check_ajax_referer('backwpup_ajax_nonce');
     //get mail settings
     $emailmethod = 'mail';
     $emailsendmail = '';
     $emailhost = '';
     $emailhostport = '';
     $emailsecure = '';
     $emailuser = '';
     $emailpass = '';
     if (empty($_POST['emailmethod'])) {
         //do so if i'm the wp_mail to get the settings
         global $phpmailer;
         // (Re)create it, if it's gone missing
         if (!is_object($phpmailer) || !$phpmailer instanceof PHPMailer) {
             require_once ABSPATH . WPINC . '/class-phpmailer.php';
             require_once ABSPATH . WPINC . '/class-smtp.php';
             $phpmailer = new PHPMailer(true);
         }
         //only if PHPMailer really used
         if (is_object($phpmailer)) {
             do_action_ref_array('phpmailer_init', array(&$phpmailer));
             //get settings from PHPMailer
             $emailmethod = $phpmailer->Mailer;
             $emailsendmail = $phpmailer->Sendmail;
             $emailhost = $phpmailer->Host;
             $emailhostport = $phpmailer->Port;
             $emailsecure = $phpmailer->SMTPSecure;
             $emailuser = $phpmailer->Username;
             $emailpass = $phpmailer->Password;
         }
     } else {
         $emailmethod = $_POST['emailmethod'];
         $emailsendmail = $_POST['emailsendmail'];
         $emailhost = $_POST['emailhost'];
         $emailhostport = $_POST['emailhostport'];
         $emailsecure = $_POST['emailsecure'];
         $emailuser = $_POST['emailuser'];
         $emailpass = BackWPup_Encryption::decrypt($_POST['emailpass']);
     }
     //Generate mail with Swift Mailer
     if (function_exists('mb_internal_encoding') && (int) ini_get('mbstring.func_overload') & 2) {
         $mbEncoding = mb_internal_encoding();
         mb_internal_encoding('ASCII');
     }
     try {
         //Set Temp dir for mailing
         Swift_Preferences::getInstance()->setTempDir(untrailingslashit(BackWPup::get_plugin_data('TEMP')))->setCacheType('disk');
         // Create the Transport
         if ($emailmethod == 'smtp') {
             $transport = Swift_SmtpTransport::newInstance($emailhost, $emailhostport);
             $transport->setUsername($emailuser);
             $transport->setPassword($emailpass);
             if ($emailsecure == 'ssl') {
                 $transport->setEncryption('ssl');
             }
             if ($emailsecure == 'tls') {
                 $transport->setEncryption('tls');
             }
         } elseif ($emailmethod == 'sendmail') {
             $transport = Swift_SendmailTransport::newInstance($emailsendmail);
         } else {
             $transport = Swift_MailTransport::newInstance();
         }
         // Create the Mailer using your created Transport
         $emailer = Swift_Mailer::newInstance($transport);
         // Create a message
         $message = Swift_Message::newInstance(__('BackWPup archive sending TEST Message', 'backwpup'));
         $message->setFrom(array($_POST['emailsndemail'] => isset($_POST['emailsndemailname']) ? $_POST['emailsndemailname'] : ''));
         $message->setTo(array($_POST['emailaddress']));
         $message->setBody(__('If this message reaches your inbox, sending backup archives via email should work for you.', 'backwpup'));
         // Send the message
         $result = $emailer->send($message);
     } catch (Exception $e) {
         echo '<span id="emailsendtext" style="color:red;">Swift Mailer: ' . $e->getMessage() . '</span>';
     }
     if (isset($mbEncoding)) {
         mb_internal_encoding($mbEncoding);
     }
     if (!isset($result) || !$result) {
         echo '<span id="emailsendtext" style="color:red;">' . __('Error while sending email!', 'backwpup') . '</span>';
     } else {
         echo '<span id="emailsendtext" style="color:green;">' . __('Email sent.', 'backwpup') . '</span>';
     }
     die;
 }
Ejemplo n.º 21
0
 function wp_mail($to, $subject, $message, $headers = '', $attachments = array(), $echo_error = false)
 {
     global $st_smtp_config;
     // Compact the input, apply the filters, and extract them back out
     extract(apply_filters('wp_mail', compact('to', 'subject', 'message', 'headers', 'attachments')));
     if (!is_array($attachments)) {
         $attachments = explode("\n", str_replace("\r\n", "\n", $attachments));
     }
     require_once 'Swift/lib/swift_required.php';
     $sender_email = "";
     $sender_name = "";
     $reply_to = "";
     // mixed
     // Headers
     if (empty($headers)) {
         $headers = array();
     } else {
         if (!is_array($headers)) {
             // Explode the headers out, so this function can take both
             // string headers and an array of headers.
             $tempheaders = explode("\n", str_replace("\r\n", "\n", $headers));
         } else {
             $tempheaders = $headers;
         }
         $headers = array();
         $cc = array();
         $bcc = array();
         // If it's actually got contents
         if (!empty($tempheaders)) {
             // Iterate through the raw headers
             foreach ((array) $tempheaders as $header) {
                 if (strpos($header, ':') === false) {
                     if (false !== stripos($header, 'boundary=')) {
                         $parts = preg_split('/boundary=/i', trim($header));
                         $boundary = trim(str_replace(array("'", '"'), '', $parts[1]));
                     }
                     continue;
                 }
                 // Explode them out
                 list($name, $content) = explode(':', trim($header), 2);
                 // Cleanup crew
                 $name = trim($name);
                 $content = trim($content);
                 switch (strtolower($name)) {
                     // Sender: is only one, is the one that actually send the email, mandatory in case of multiple From:
                     // see: https://tools.ietf.org/html/rfc2822#section-3.6.2
                     case 'sender':
                         if (strpos($content, '<') !== false) {
                             // So... making my life hard again?
                             $sender_name = substr($content, 0, strpos($content, '<') - 1);
                             $sender_name = str_replace('"', '', $sender_name);
                             $sender_name = trim($sender_name);
                             $sender_email = substr($content, strpos($content, '<') + 1);
                             $sender_email = str_replace('>', '', $sender_email);
                             $sender_email = trim($sender_email);
                         } else {
                             $sender_email = trim($content);
                         }
                         break;
                         // Mainly for legacy -- process a From: header if it's there
                     // Mainly for legacy -- process a From: header if it's there
                     case 'from':
                         if (strpos($content, '<') !== false) {
                             // So... making my life hard again?
                             $from_name = substr($content, 0, strpos($content, '<') - 1);
                             $from_name = str_replace('"', '', $from_name);
                             $from_name = trim($from_name);
                             $from_email = substr($content, strpos($content, '<') + 1);
                             $from_email = str_replace('>', '', $from_email);
                             $from_email = trim($from_email);
                         } else {
                             $from_email = trim($content);
                         }
                         break;
                     case 'reply-to':
                         if (strpos($content, '<') !== false) {
                             // So... making my life hard again?
                             $reply_to_name = substr($content, 0, strpos($content, '<') - 1);
                             $reply_to_name = str_replace('"', '', $reply_to_name);
                             $reply_to_name = trim($reply_to_name);
                             $reply_to_email = substr($content, strpos($content, '<') + 1);
                             $reply_to_email = str_replace('>', '', $reply_to_email);
                             $reply_to_email = trim($reply_to_email);
                             $reply_to = array($reply_to_email => $reply_to_name);
                         } else {
                             $reply_to = trim($content);
                         }
                         break;
                     case 'content-type':
                         if (strpos($content, ';') !== false) {
                             list($type, $charset) = explode(';', $content);
                             $content_type = trim($type);
                             if (false !== stripos($charset, 'charset=')) {
                                 $charset = trim(str_replace(array('charset=', '"'), '', $charset));
                             } elseif (false !== stripos($charset, 'boundary=')) {
                                 $boundary = trim(str_replace(array('BOUNDARY=', 'boundary=', '"'), '', $charset));
                                 $charset = '';
                             }
                         } else {
                             $content_type = trim($content);
                         }
                         break;
                     case 'cc':
                         $cc = array_merge((array) $cc, explode(',', $content));
                         break;
                     case 'bcc':
                         $bcc = array_merge((array) $bcc, explode(',', $content));
                         break;
                     default:
                         // Add it to our grand headers array
                         $headers[trim($name)] = trim($content);
                         break;
                 }
             }
         }
     }
     // overwriting if specified or necessary
     if ($st_smtp_config['overwrite_sender'] == "overwrite_always") {
         $from_name = $st_smtp_config['sender_name'];
         $from_email = $st_smtp_config['sender_mail'];
         // overwrite sender only in case of need
         if (!empty($sender_name) || !empty($sender_email)) {
             $sender_name = $from_name;
             $sender_email = $from_email;
         }
     }
     // From email and name
     // If we don't have a name from the input headers
     if (empty($from_name)) {
         $from_name = 'WordPress';
     }
     /* If we don't have an email from the input headers default to wordpress@$sitename
      * Some hosts will block outgoing mail from this address if it doesn't exist but
      * there's no easy alternative. Defaulting to admin_email might appear to be another
      * option but some hosts may refuse to relay mail from an unknown domain. See
      * http://trac.wordpress.org/ticket/5007.
      */
     // Get the site domain and get rid of www.
     $sitename = strtolower($_SERVER['SERVER_NAME']);
     if (substr($sitename, 0, 4) == 'www.') {
         $sitename = substr($sitename, 4);
     }
     $wp_from_email = 'wordpress@' . $sitename;
     if (empty($from_email) || $from_email == $wp_from_email) {
         if ($st_smtp_config['overwrite_sender'] == "overwrite_wp_default" && !empty($st_smtp_config['sender_mail'])) {
             $from_name = $st_smtp_config['sender_name'];
             $from_email = $st_smtp_config['sender_mail'];
         } else {
             $from_email = $wp_from_email;
         }
     }
     if (!empty($sender_email) && $sender_email == $wp_from_email && $st_smtp_config['overwrite_sender'] == "overwrite_wp_default" && !empty($st_smtp_config['sender_mail'])) {
         $sender_name = $st_smtp_config['sender_name'];
         $sender_email = $st_smtp_config['sender_mail'];
     }
     //Create a message
     $message = Swift_Message::newInstance($subject)->setFrom(array(apply_filters('wp_mail_from', $from_email) => apply_filters('wp_mail_from_name', $from_name)))->setBody($message);
     // Set the sender, which may be different than the from field
     if (!empty($sender_email)) {
         $message->setSender(array($sender_email => $sender_name));
     }
     // Set the reply-to
     if (!empty($reply_to)) {
         $message->setReplyTo($reply_to);
     }
     // Set destination addresses
     if (!is_array($to)) {
         $to = explode(',', $to);
     }
     foreach ((array) $to as $recipient) {
         // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>"
         $recipient_name = '';
         if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) {
             if (count($matches) == 3) {
                 $recipient_name = $matches[1];
                 $recipient = $matches[2];
             }
         }
         // leave the name null if empty
         if (empty($recipient_name)) {
             $message->addTo(trim($recipient));
         } else {
             $message->addTo(trim($recipient), $recipient_name);
         }
     }
     // Add any CC and BCC recipients
     if (!empty($cc)) {
         foreach ((array) $cc as $recipient) {
             // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>"
             $recipient_name = '';
             if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) {
                 if (count($matches) == 3) {
                     $recipient_name = $matches[1];
                     $recipient = $matches[2];
                 }
             }
             // leave the name null if empty
             if (empty($recipient_name)) {
                 $message->addCc(trim($recipient));
             } else {
                 $message->addCc(trim($recipient), $recipient_name);
             }
         }
     }
     if (!empty($bcc)) {
         foreach ((array) $bcc as $recipient) {
             // Break $recipient into name and address parts if in the format "Foo <*****@*****.**>"
             $recipient_name = '';
             if (preg_match('/(.*)<(.+)>/', $recipient, $matches)) {
                 if (count($matches) == 3) {
                     $recipient_name = $matches[1];
                     $recipient = $matches[2];
                 }
             }
             // leave the name null if empty
             if (empty($recipient_name)) {
                 $message->addBcc(trim($recipient));
             } else {
                 $message->addBcc(trim($recipient), $recipient_name);
             }
         }
     }
     // Set Content-Type and charset
     // If we don't have a content-type from the input headers
     if (empty($content_type)) {
         $content_type = 'text/plain';
     }
     $content_type = apply_filters('wp_mail_content_type', $content_type);
     $message->setContentType($content_type);
     // If we don't have a charset from the input headers
     if (!isset($charset)) {
         $charset = get_bloginfo('charset');
     }
     // Set the content-type and charset
     Swift_Preferences::getInstance()->setCharset(apply_filters('wp_mail_charset', $charset));
     // Set custom headers
     if (!empty($headers)) {
         $msg_headers = $message->getHeaders();
         foreach ((array) $headers as $name => $content) {
             $msg_headers->addTextHeader($name, $content);
         }
         if (false !== stripos($content_type, 'multipart') && !empty($boundary)) {
             $msg_headers->addTextHeader("Content-Type", sprint("%s;\n\t boundary=\"%s\"", $content_type, $boundary));
         }
     }
     if (!empty($attachments)) {
         foreach ($attachments as $attachment) {
             // bug in Swift Mailer https://github.com/swiftmailer/swiftmailer/issues/274
             // they claim they fixed it, but at the end they throw the exception too late
             // we want to never fail for this silly error
             if (!is_readable($attachment)) {
                 continue;
             }
             try {
                 $message->attach(Swift_Attachment::fromPath($attachment));
             } catch (Swift_IoException $e) {
                 continue;
             }
         }
     }
     // default server if none inserted
     if (empty($st_smtp_config['server'])) {
         $st_smtp_config['server'] = "localhost";
     }
     // default port if none inserted
     if (empty($st_smtp_config['port'])) {
         $st_smtp_config['port'] = 25;
     }
     // we should try first and _maybe_ echo failure error
     try {
         // Create the Transport then call setUsername() and setPassword()
         $transport = Swift_SmtpTransport::newInstance($st_smtp_config['server'], $st_smtp_config['port']);
         if (!empty($st_smtp_config['ssl'])) {
             $transport->setEncryption($st_smtp_config['ssl']);
         }
         if (!empty($st_smtp_config['username'])) {
             $transport->setUsername($st_smtp_config['username']);
         }
         if (!empty($st_smtp_config['password'])) {
             $transport->setPassword($st_smtp_config['password']);
         }
         // Create the Mailer using your created Transport
         $mailer = Swift_Mailer::newInstance($transport);
         // Send!
         $result = $mailer->send($message, $failures);
     } catch (Exception $e) {
         $result = false;
         if ($echo_error) {
             echo $e->getMessage();
         }
     }
     return $result;
 }
Ejemplo n.º 22
0
function swiftmailer_configurator()
{
    // Set the default character set for everything
    Swift_Preferences::getInstance()->setCharset(Kohana::$charset);
}
Ejemplo n.º 23
0
 public function setUp()
 {
     Swift_Preferences::getInstance()->setCharset(null);
     //TODO: Test with the charset defined
 }
Ejemplo n.º 24
0
     * @return  integer  number of emails sent
     */
    public function batch(array $to, array &$failed = NULL)
    {
        // Get a copy of the current message
        $message = clone $this->_message;
        // Load the mailer instance
        $mailer = Email::mailer();
        // Count the total number of messages sent
        $total = 0;
        foreach ($to as $email => $name) {
            if (ctype_digit((string) $email)) {
                // Only an email address was provided
                $email = $name;
                $name = NULL;
            }
            // Set the To addre
            $message->setTo($email, $name);
            // Send this email
            $total += $mailer->send($message, $failed);
        }
        return $total;
    }
}
// End email
// Load Swiftmailer
require Kohana::find_file('vendor/swiftmailer', 'lib/swift_required');
if (method_exists('Swift_Preferences', 'getInstance')) {
    // Set the default character set for everything
    Swift_Preferences::getInstance()->setCharset(Kohana::$charset);
}
Ejemplo n.º 25
0
 public function initMailer()
 {
     // メール送信時の文字エンコード指定(デフォルトはUTF-8)
     if (isset($this['config']['mail']['charset_iso_2022_jp']) && is_bool($this['config']['mail']['charset_iso_2022_jp'])) {
         if ($this['config']['mail']['charset_iso_2022_jp'] === true) {
             \Swift::init(function () {
                 \Swift_DependencyContainer::getInstance()->register('mime.qpheaderencoder')->asAliasOf('mime.base64headerencoder');
                 \Swift_Preferences::getInstance()->setCharset('iso-2022-jp');
             });
         }
     }
     $this->register(new \Silex\Provider\SwiftmailerServiceProvider());
     $this['swiftmailer.options'] = $this['config']['mail'];
     if (isset($this['config']['mail']['spool']) && is_bool($this['config']['mail']['spool'])) {
         $this['swiftmailer.use_spool'] = $this['config']['mail']['spool'];
     }
     // デフォルトはsmtpを使用
     $transport = $this['config']['mail']['transport'];
     if ($transport == 'sendmail') {
         $this['swiftmailer.transport'] = \Swift_SendmailTransport::newInstance();
     } elseif ($transport == 'mail') {
         $this['swiftmailer.transport'] = \Swift_MailTransport::newInstance();
     }
 }
Ejemplo n.º 26
0
 /**
  * Constructor.
  *
  * Available options:
  *
  *  * charset: The default charset to use for messages
  *  * logging: Whether to enable logging or not
  *  * delivery_strategy: The delivery strategy to use
  *  * spool_class: The spool class (for the spool strategy)
  *  * spool_arguments: The arguments to pass to the spool constructor
  *  * delivery_address: The email address to use for the single_address strategy
  *  * transport: The main transport configuration
  *  *   * class: The main transport class
  *  *   * param: The main transport parameters
  *
  * @param sfEventDispatcher $dispatcher An event dispatcher instance
  * @param array             $options    An array of options
  */
 public function __construct(sfEventDispatcher $dispatcher, $options)
 {
     // options
     $options = array_merge(array('charset' => 'UTF-8', 'logging' => false, 'delivery_strategy' => 'realtime', 'transport' => array('class' => 'Swift_MailTransport', 'param' => array())), $options);
     $constantName = 'sfMailer::' . strtoupper($options['delivery_strategy']);
     $this->strategy = defined($constantName) ? constant($constantName) : false;
     if (!$this->strategy) {
         throw new InvalidArgumentException(sprintf('Unknown mail delivery strategy "%s" (should be one of realtime, spool, single_address, or none)', $options['delivery_strategy']));
     }
     // transport
     $class = $options['transport']['class'];
     $transport = new $class();
     if (isset($options['transport']['param'])) {
         foreach ($options['transport']['param'] as $key => $value) {
             $method = 'set' . ucfirst($key);
             if (method_exists($transport, $method)) {
                 $transport->{$method}($value);
             } elseif (method_exists($transport, 'getExtensionHandlers')) {
                 foreach ($transport->getExtensionHandlers() as $handler) {
                     if (in_array(strtolower($method), array_map('strtolower', (array) $handler->exposeMixinMethods()))) {
                         $transport->{$method}($value);
                     }
                 }
             }
         }
     }
     $this->realtimeTransport = $transport;
     if (sfMailer::SPOOL == $this->strategy) {
         if (!isset($options['spool_class'])) {
             throw new InvalidArgumentException('For the spool mail delivery strategy, you must also define a spool_class option');
         }
         $arguments = isset($options['spool_arguments']) ? $options['spool_arguments'] : array();
         if ($arguments) {
             $r = new ReflectionClass($options['spool_class']);
             $this->spool = $r->newInstanceArgs($arguments);
         } else {
             $this->spool = new $options['spool_class']();
         }
         $transport = new Swift_SpoolTransport($this->spool);
     } elseif (sfMailer::SINGLE_ADDRESS == $this->strategy) {
         if (!isset($options['delivery_address'])) {
             throw new InvalidArgumentException('For the single_address mail delivery strategy, you must also define a delivery_address option');
         }
         $this->address = $options['delivery_address'];
         $transport->registerPlugin($this->redirectingPlugin = new Swift_Plugins_RedirectingPlugin($this->address));
     }
     parent::__construct($transport);
     // logger
     if ($options['logging']) {
         $this->logger = new sfMailerMessageLoggerPlugin($dispatcher);
         $transport->registerPlugin($this->logger);
     }
     if (sfMailer::NONE == $this->strategy) {
         // must be registered after logging
         $transport->registerPlugin(new Swift_Plugins_BlackholePlugin());
     }
     // preferences
     Swift_Preferences::getInstance()->setCharset($options['charset']);
     $dispatcher->notify(new sfEvent($this, 'mailer.configure'));
 }
Ejemplo n.º 27
0
<?php

/****************************************************************************/
/*                                                                          */
/* YOU MAY WISH TO MODIFY OR REMOVE THE FOLLOWING LINES WHICH SET DEFAULTS  */
/*                                                                          */
/****************************************************************************/

// Sets the default charset so that setCharset() is not needed elsewhere
Swift_Preferences::getInstance()->setCharset('utf-8');

// Without these lines the default caching mechanism is "array" but this uses
// a lot of memory.
// If possible, use a disk cache to enable attaching large attachments etc
// if (function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir()))
// {
//   Swift_Preferences::getInstance()
//     -> setTempDir(sys_get_temp_dir())
//     -> setCacheType('disk');
// }
Ejemplo n.º 28
0
<?php

/****************************************************************************/
/*                                                                          */
/* YOU MAY WISH TO MODIFY OR REMOVE THE FOLLOWING LINES WHICH SET DEFAULTS  */
/*                                                                          */
/****************************************************************************/
// Sets the default charset so that setCharset() is not needed elsewhere
Swift_Preferences::getInstance()->setCharset('UTF-8');
// Without these lines the default caching mechanism is "array" but this uses
// a lot of memory.
// If possible, use a disk cache to enable attaching large attachments etc
if (function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir())) {
    Swift_Preferences::getInstance()->setTempDir(sys_get_temp_dir())->setCacheType('disk');
}
Ejemplo n.º 29
0
<?php

/****************************************************************************/
/*                                                                          */
/* YOU MAY WISH TO MODIFY OR REMOVE THE FOLLOWING LINES WHICH SET DEFAULTS  */
/*                                                                          */
/****************************************************************************/
// Sets the default charset so that setCharset() is not needed elsewhere
Swift_Preferences::getInstance()->setCharset('utf-8');
// Without these lines the default caching mechanism is "array" but this uses a lot of memory.
// If possible, use a disk cache to enable attaching large attachments etc.
// You can override the default temporary directory by setting the TMPDIR environment variable.
// The @ operator in front of is_writable calls is to avoid PHP warnings
// when using open_basedir
$tmp = getenv('TMPDIR');
if ($tmp && @is_writable($tmp)) {
    Swift_Preferences::getInstance()->setTempDir($tmp)->setCacheType('disk');
} elseif (function_exists('sys_get_temp_dir') && @is_writable(sys_get_temp_dir())) {
    Swift_Preferences::getInstance()->setTempDir(sys_get_temp_dir())->setCacheType('disk');
}
Swift_Preferences::getInstance()->setQPDotEscape(false);
Ejemplo n.º 30
0
    /**
     * Initialise.
     *
     * Runs ar plugin init time.
     *
     * @throws InvalidArgumentException If invalid configuration given.
     *
     * @return void
     */
    public function initialize()
    {
        define('SWIFT_REQUIRED_LOADED', true);
        define('SWIFT_INIT_LOADED', true);

        // register namespace
        ZLoader::addAutoloader('Swift', dirname(__FILE__) . '/lib/vendor/SwiftMailer/classes');

        // initialize Swift
        //require_once realpath($this->baseDir . '/lib/vendor/SwiftMailer/swift_init.php'); // dont use this as it fails in virtual hosting environments with open_basedir restrictions
        // Load in dependency maps
        require_once dirname(__FILE__) . '/lib/vendor/SwiftMailer/dependency_maps/cache_deps.php';
        require_once dirname(__FILE__) . '/lib/vendor/SwiftMailer/dependency_maps/mime_deps.php';
        require_once dirname(__FILE__) . '/lib/vendor/SwiftMailer/dependency_maps/transport_deps.php';

        // load configuration (todo: move this to persistence).
        include dirname(__FILE__) . '/configuration/config.php';

        $this->serviceManager['swiftmailer.preferences.sendmethod'] = $config['sendmethod'];

        $preferences = Swift_Preferences::getInstance();
        $this->serviceManager['swiftmailer.preferences.charset'] = $config['charset'];
        $this->serviceManager['swiftmailer.preferences.cachetype'] = $config['cachetype'];
        $this->serviceManager['swiftmailer.preferences.tempdir'] = $config['tempdir'];
        $preferences->setCharset($config['charset']);
        $preferences->setCacheType($config['cachetype']);
        $preferences->setTempDir($config['tempdir']);

        // determine the correct transport
        $type = $config['transport']['type'];
        $args = $config['transport'][$type];
        switch ($type) {
            case 'mail':
                $this->serviceManager['swiftmailer.transport.mail.extraparams'] = $args['extraparams'];
                $definition = new Zikula_ServiceManager_Definition('Swift_MailTransport', array(new Zikula_ServiceManager_Argument('swiftmailer.transport.mail.extraparams')));
                break;

            case 'smtp':
                $this->serviceManager['swiftmailer.transport.smtp.host'] = $args['host'];
                $this->serviceManager['swiftmailer.transport.smtp.port'] = $args['port'];
                $definition = new Zikula_ServiceManager_Definition('Swift_SmtpTransport', array(
                                new Zikula_ServiceManager_Argument('swiftmailer.transport.smtp.host'),
                                new Zikula_ServiceManager_Argument('swiftmailer.transport.smtp.port')));

                if ($args['username'] && $args['password']) {
                    $this->serviceManager['swiftmailer.transport.smtp.username'] = $args['username'];
                    $this->serviceManager['swiftmailer.transport.smtp.password'] = $args['password'];
                    $definition->addMethod('setUserName', new Zikula_ServiceManager_Argument('swiftmailer.transport.smtp.username'));
                    $definition->addMethod('setPassword', new Zikula_ServiceManager_Argument('swiftmailer.transport.smtp.password'));
                }
                if (isset($args['encryption'])) {
                    $this->serviceManager['swiftmailer.transport.smtp.encryption'] = $args['encryption'];
                    $definition->addMethod('setEncryption', new Zikula_ServiceManager_Argument('swiftmailer.transport.smtp.encryption'));
                }
                break;

            case 'sendmail':
                $this->serviceManager['swiftmailer.transport.mail.command'] = $args['command'];
                $definition = new Zikula_ServiceManager_Definition('Swift_SendmailTransport', array(new Zikula_ServiceManager_Argument('swiftmailer.transport.mail.command')));
                break;

            default:
                // error
                throw new InvalidArgumentException('Invalid transport type, must be mail, smtp or sendmail');
                break;
        }

        // register transport
        $this->serviceManager->registerService('swiftmailer.transport', $definition);

        // define and register mailer using transport service
        $definition = new Zikula_ServiceManager_Definition('Swift_Mailer', array(new Zikula_ServiceManager_Reference('swiftmailer.transport')));
        $this->serviceManager->registerService('mailer', $definition, false);

        // register simple mailer service
        $definition = new Zikula_ServiceManager_Definition('SystemPlugins_SwiftMailer_Mailer', array(new Zikula_ServiceManager_Reference('zikula.servicemanager')));
        $this->serviceManager->registerService('mailer.simple', $definition);
    }