Author: Chris Corbyn
Inheritance: implements Swift_Plugins_Logger
示例#1
0
 /**
  * Send an email via the transport.
  * @param Swift_Message	message 	email
  * @return 							number of messages sent
  */
 public function sendMessage($message)
 {
     $mailer = Swift_Mailer::newInstance($this->transport);
     $this->dump = '';
     $logger = new Swift_Plugins_Loggers_ArrayLogger();
     $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
     try {
         return $mailer->send($message);
     } catch (Excpetion $e) {
         $this->dump = $e->getMessage() . ' -- ' . $logger->dump();
         return 0;
     }
 }
示例#2
0
 /**
  * Returns the debug log.
  * Note that SwiftMailer requires you set 'Debug: true' in your config.
  * @return array
  * @throws MailerException
  */
 public function getDebugLog()
 {
     if (empty($this->logger)) {
         throw new MailerException('Logger is not turned on in the config.');
     }
     return $this->logger->dump();
 }
示例#3
0
 /**
  * Send the specified message. Also sets the from address to the value defined in config.php
  * if no-one has been passed.
  *
  * @param Message $message Message to send
  * @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and
  * therefore should be considered
  * @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address
  * has been supplied.)
  */
 public function send(Message $message)
 {
     $debugMode = $this->config->getSystemValue('mail_smtpdebug', false);
     if (sizeof($message->getFrom()) === 0) {
         $message->setFrom([\OCP\Util::getDefaultEmailAddress($this->defaults->getName())]);
     }
     $failedRecipients = [];
     $mailer = $this->getInstance();
     // Enable logger if debug mode is enabled
     if ($debugMode) {
         $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger();
         $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger));
     }
     $mailer->send($message->getSwiftMessage(), $failedRecipients);
     // Debugging logging
     $logMessage = sprintf('Sent mail to "%s" with subject "%s"', print_r($message->getTo(), true), $message->getSubject());
     $this->logger->debug($logMessage, ['app' => 'core']);
     if ($debugMode && isset($mailLogger)) {
         $this->logger->debug($mailLogger->dump(), ['app' => 'core']);
     }
     return $failedRecipients;
 }
示例#4
0
 /**
  * Log exception
  *
  * @param \Exception|string $error
  */
 protected function logError($error)
 {
     if ($error instanceof \Exception) {
         $error = $error->getMessage();
         $this->fatal = true;
     }
     $logDump = $this->logger->dump();
     if (!empty($logDump) && strpos($error, $logDump) === false) {
         $error .= " Log data: {$logDump}";
     }
     $this->errors[] = $error;
     $this->logger->clear();
     $this->factory->getLogger()->log('error', '[MAIL ERROR] ' . $error);
 }
示例#5
0
 /**
  * Log exception
  *
  * @param \Exception|string $error
  */
 private function logError($error)
 {
     if ($error instanceof \Exception) {
         $error = $error->getMessage();
         $this->fatal = true;
     }
     $this->errors[] = $error;
     $logDump = $this->logger->dump();
     if (!empty($logDump)) {
         $error .= "; {$logDump}";
         $this->logger->clear();
     }
     $this->factory->getLogger()->log('error', '[MAIL ERROR] ' . $error);
 }
 public function testLengthCanBeTruncated()
 {
     $logger = new Swift_Plugins_Loggers_ArrayLogger(2);
     $logger->add(">> FOO\r\n");
     $logger->add("<< 502 That makes no sense\r\n");
     $logger->add(">> RSET\r\n");
     $logger->add("<< 250 OK\r\n");
     $this->assertEqual(">> RSET\r\n" . PHP_EOL . "<< 250 OK\r\n", $logger->dump(), '%s: Log should be truncated to last 2 entries');
 }
示例#7
0
 /**
  * Tests mail transport settings
  *
  * @param Request $request
  *
  * @return JsonResponse
  */
 protected function testEmailServerConnectionAction(Request $request)
 {
     $dataArray = array('success' => 0, 'error' => '');
     if ($this->factory->getUser()->isAdmin()) {
         $settings = $request->request->all();
         $transport = $settings['transport'];
         switch ($transport) {
             case 'mautic.transport.mandrill':
                 $mailer = new MandrillTransport();
                 break;
             case 'mautic.transport.sendgrid':
                 $mailer = new SendgridTransport();
                 break;
             case 'mautic.transport.amazon':
                 $mailer = new AmazonTransport();
                 break;
             case 'mautic.transport.postmark':
                 $mailer = new PostmarkTransport();
                 break;
             case 'gmail':
                 $mailer = new \Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl');
                 break;
             case 'smtp':
                 $mailer = new \Swift_SmtpTransport($settings['host'], $settings['port'], $settings['encryption']);
                 break;
         }
         if (method_exists($mailer, 'setMauticFactory')) {
             $mailer->setMauticFactory($this->factory);
         }
         if (!empty($mailer)) {
             if (empty($settings['password'])) {
                 $settings['password'] = $this->factory->getParameter('mailer_password');
             }
             $mailer->setUsername($settings['user']);
             $mailer->setPassword($settings['password']);
             $logger = new \Swift_Plugins_Loggers_ArrayLogger();
             $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
             try {
                 $mailer->start();
                 $translator = $this->factory->getTranslator();
                 if ($settings['send_test'] == 'true') {
                     $message = new \Swift_Message($translator->trans('mautic.core.config.form.mailer.transport.test_send.subject'), $translator->trans('mautic.core.config.form.mailer.transport.test_send.body'));
                     $user = $this->factory->getUser();
                     $message->setFrom(array($settings['from_email'] => $settings['from_name']));
                     $message->setTo(array($user->getEmail() => $user->getFirstName() . ' ' . $user->getLastName()));
                     $mailer->send($message);
                 }
                 $dataArray['success'] = 1;
                 $dataArray['message'] = $translator->trans('mautic.core.success');
             } catch (\Exception $e) {
                 $dataArray['message'] = $e->getMessage() . '<br />' . $logger->dump();
             }
         }
     }
     return $this->sendJsonResponse($dataArray);
 }
示例#8
0
function email($fromAddress, $toAddress, $subject, $bodyHtml, $bodyText, $senderAddress = NULL, $returnAddress = NULL)
{
    /*
    Send an email using the Swift Mailer class library. Returns true if sent successfully, false otherwise.
    $fromAddress = (string, array, associative array) one or more senders' email addresses. The email will show as coming from this address. Array structure is array('*****@*****.**' => 'Joe Bob'). Strings will be converted to an array.
    $toAddress = (string, array, associative array) recipients' email addresses. Array structure is array('*****@*****.**' => 'Joe Bob'). Strings will be converted to an array.
    $subject = (string) the subject of the email.
    $bodyHtml = (string) the body or message of the email. May contain HTML.
    $bodyText = (string) the text version of the message. Should not contain HTML.
    $senderAddress = (string) optional single email address of the sender, not necessarily the creator of the message. This address is visible in the message headers, will be seen by the recipients, and will be used as the Return-Path: unless otherwise specified. Default is EMAILDONOTREPLY set in config.php.
    $returnAddress = (string) an optional single email address to handle bounced emails. This address specifies where bounce notifications should be sent and is set with the setReturnPath() method of the message. You can use only one email address and it must not include a personal name. Default is EMAILDONOTREPLY defined in config.php.
    */
    require_once 'Classes/Swift/swift_init.php';
    global $debug, $message;
    if ((array) $fromAddress === $fromAddress) {
        $thisCount = 0;
        $newFromAddress = array();
        foreach ($fromAddress as $key) {
            //Add valid email addresses to the new array.
            if (emailValidate($key) === true) {
                $newFromAddress[] = $key;
            } elseif ($thisCount == 0) {
                error(__LINE__, '', "The to address '{$fromAddress}' is not valid.<br>");
                return false;
            }
            $thisCount++;
        }
        $fromAddress = $newFromAddress;
    } else {
        if (emailValidate($fromAddress) === true) {
            $fromAddress = array($fromAddress);
        } else {
            error(__LINE__, '', "The to address '{$fromAddress}' is not valid.<br>");
            return false;
        }
    }
    if ((array) $toAddress === $toAddress) {
        $thisCount = 0;
        $newToAddress = array();
        foreach ($toAddress as $key) {
            //Add valid email addresses to the new array.
            if (emailValidate($key) === true) {
                $newToAddress[] = $key;
            } elseif ($thisCount == 0) {
                error(__LINE__, '', "The to address '{$toAddress}' is not valid.<br>");
                return false;
            }
            $thisCount++;
        }
        $toAddress = $newToAddress;
    } else {
        if (emailValidate($toAddress) === true) {
            $toAddress = array($toAddress);
        } else {
            error(__LINE__, '', "The to address '{$toAddress}' is not valid.<br>");
            return false;
        }
    }
    $debug->add('$senderAddress before validation: ' . "{$senderAddress}");
    $senderAddress = emailValidate($senderAddress) ? $senderAddress : EMAILDONOTREPLY;
    $returnAddress = emailValidate($returnAddress) ? $returnAddress : EMAILDONOTREPLY;
    $debug->add('$senderAddress after validation: ' . "{$senderAddress}");
    //Create the message
    $email = Swift_Message::newInstance()->setFrom($fromAddress)->setTo($toAddress)->setSubject($subject)->addPart('<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF" marginheight="0" marginwidth="0" text="#000000" topmargin="0">
<table width="800" cellpadding="10" cellspacing="0" border="0" align="center" bgcolor="#FFFFFF">
	<tr>
		<td align="left">' . buildHeaderForEmail() . '</td>
	</tr>
	<tr>
		<td align="left"><font face="' . FONT . '" size="3">' . $bodyHtml . '
			<br>
			<br>
			Sincerly,<br>
			<br>
			' . THENAMEOFTHESITE . '
			<br>
			<br></font>
		</td>
	</tr>
	<tr>
		<td align="center"><font face="' . FONT . '" size="' . SIZE1 . '">This is an automated message. Please do not reply.</font><br><br>
<a href="' . LINKSUPPORT . '">Click here to contact support.</a></td>
	</tr>
</table>		
</body>
</html>', 'text/html')->setBody($bodyText . '
Sincerly,

' . THENAMEOFTHESITE . ' Support


This is an automated message. Please do not reply.')->setSender($senderAddress)->setReturnPath($returnAddress);
    if (LOCAL) {
        //$transport = Swift_SmtpTransport::newInstance('127.0.0.0', 25);//Doesn't work on local machine.
        $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
        //This uses the local machine's MTA, not a remote service.
        //$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')->setUsername('*****@*****.**')->setPassword('');//This uses a remote service like gmail for secure mail transactions.
    } else {
        $transport = Swift_SendmailTransport::newInstance('/usr/sbin/exim -bs');
        //This works better with ServInt.
    }
    $mailer = Swift_Mailer::newInstance($transport);
    //To use the ArrayLogger.
    $logger = new Swift_Plugins_Loggers_ArrayLogger();
    $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
    if ($mailer->send($email, $failures)) {
        return true;
    } else {
        $debug->printArray($failures, 'email address undeliverable');
        return false;
    }
    //Dump the error log.
    $debug->add($logger->dump());
}
示例#9
0
 /**
  *
  * @todo Save to sent items should be implemented as a Swift outputstream for better memory management
  * @param type $params
  * @return boolean
  */
 protected function actionSend($params)
 {
     //HARDCODE FIX FOR RV ERROR
     $params['forward_mailbox'] = "";
     $params['forward_uid'] = 0;
     GO::session()->closeWriting();
     $response['success'] = true;
     $response['feedback'] = '';
     $alias = \GO\Email\Model\Alias::model()->findByPk($params['alias_id']);
     $account = Account::model()->findByPk($alias->account_id);
     $message = new \GO\Base\Mail\SmimeMessage();
     $tag = $this->_createAutoLinkTagFromParams($params, $account);
     if (!empty($tag)) {
         if ($params['content_type'] == 'html') {
             $params['htmlbody'] .= '<div style="display:none">' . $tag . '</div>';
         } else {
             $params['plainbody'] .= "\n\n" . $tag . "\n\n";
         }
     }
     $message->handleEmailFormInput($params);
     $recipientCount = $message->countRecipients();
     if (!$recipientCount) {
         throw new \Exception(GO::t('feedbackNoReciepent', 'email'));
     }
     $message->setFrom($alias->email, $alias->name);
     $mailer = \GO\Base\Mail\Mailer::newGoInstance(\GO\Email\Transport::newGoInstance($account));
     $logger = new \Swift_Plugins_Loggers_ArrayLogger();
     $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
     $this->fireEvent('beforesend', array(&$this, &$response, &$message, &$mailer, $account, $alias, $params));
     $failedRecipients = array();
     $success = $mailer->send($message, $failedRecipients);
     // Update "last mailed" time of the emailed contacts.
     if ($success && GO::modules()->addressbook) {
         $toAddresses = $message->getTo();
         if (empty($toAddresses)) {
             $toAddresses = array();
         }
         $ccAddresses = $message->getCc();
         if (empty($ccAddresses)) {
             $ccAddresses = array();
         }
         $bccAddresses = $message->getBcc();
         if (empty($bccAddresses)) {
             $bccAddresses = array();
         }
         $emailAddresses = array_merge($toAddresses, $ccAddresses);
         $emailAddresses = array_merge($emailAddresses, $bccAddresses);
         foreach ($emailAddresses as $emailAddress => $fullName) {
             $findCriteria = \GO\Base\Db\FindCriteria::newInstance()->addCondition('email', $emailAddress, '=', 't', false)->addCondition('email2', $emailAddress, '=', 't', false)->addCondition('email3', $emailAddress, '=', 't', false);
             $findParams = \GO\Base\Db\FindParams::newInstance()->criteria($findCriteria);
             $contactsStmt = \GO\Addressbook\Model\Contact::model()->find($findParams);
             if ($contactsStmt) {
                 foreach ($contactsStmt as $contactModel) {
                     if ($contactModel->name == $fullName) {
                         $contactLastMailTimeModel = \GO\Email\Model\ContactMailTime::model()->findSingleByAttributes(array('contact_id' => $contactModel->id, 'user_id' => GO::user()->id));
                         if (!$contactLastMailTimeModel) {
                             $contactLastMailTimeModel = new \GO\Email\Model\ContactMailTime();
                             $contactLastMailTimeModel->contact_id = $contactModel->id;
                             $contactLastMailTimeModel->user_id = GO::user()->id;
                         }
                         $contactLastMailTimeModel->last_mail_time = time();
                         $contactLastMailTimeModel->save();
                     }
                 }
             }
         }
     }
     if (!empty($params['reply_uid'])) {
         //set \Answered flag on IMAP message
         GO::debug("Reply");
         $account2 = Account::model()->findByPk($params['reply_account_id']);
         $imap = $account2->openImapConnection($params['reply_mailbox']);
         $imap->set_message_flag(array($params['reply_uid']), "\\Answered");
     }
     if (!empty($params['forward_uid'])) {
         //set forwarded flag on IMAP message
         $account2 = Account::model()->findByPk($params['forward_account_id']);
         $imap = $account2->openImapConnection($params['forward_mailbox']);
         $imap->set_message_flag(array($params['forward_uid']), "\$Forwarded");
     }
     /**
      * if you want ignore default sent folder message will be store in
      * folder wherefrom user sent it
      */
     if ($account->ignore_sent_folder && !empty($params['reply_mailbox'])) {
         $account->sent = $params['reply_mailbox'];
     }
     if ($account->sent && $recipientCount > count($failedRecipients)) {
         GO::debug("Sent");
         //if a sent items folder is set in the account then save it to the imap folder
         $imap = $account->openImapConnection($account->sent);
         if (!$imap->append_message($account->sent, $message, "\\Seen")) {
             $response['success'] = false;
             $response['feedback'] .= 'Failed to save send item to ' . $account->sent;
         }
     }
     if (!empty($params['draft_uid'])) {
         //remove drafts on send
         $imap = $account->openImapConnection($account->drafts);
         $imap->delete(array($params['draft_uid']));
     }
     if (count($failedRecipients)) {
         $msg = GO::t('failedRecipients', 'email') . ': ' . implode(', ', $failedRecipients) . '<br /><br />';
         $logStr = $logger->dump();
         preg_match('/<< 55[0-9] .*>>/s', $logStr, $matches);
         if (isset($matches[0])) {
             $logStr = trim(substr($matches[0], 2, -2));
         }
         throw new \Exception($msg . nl2br($logStr));
     }
     //if there's an autolink tag in the message we want to link outgoing messages too.
     $tags = $this->_findAutoLinkTags($params['content_type'] == 'html' ? $params['htmlbody'] : $params['plainbody'], $account->id);
     $this->_link($params, $message, false, $tags);
     $response['unknown_recipients'] = $this->_findUnknownRecipients($params);
     return $response;
 }
示例#10
0
 /**
  * Tests mail transport settings.
  *
  * @param Request $request
  *
  * @return JsonResponse
  */
 protected function testEmailServerConnectionAction(Request $request)
 {
     $dataArray = ['success' => 0, 'message' => ''];
     $user = $this->get('mautic.helper.user')->getUser();
     if ($user->isAdmin()) {
         $settings = $request->request->all();
         $transport = $settings['transport'];
         switch ($transport) {
             case 'gmail':
                 $mailer = new \Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl');
                 break;
             case 'smtp':
                 $mailer = new \Swift_SmtpTransport($settings['host'], $settings['port'], $settings['encryption']);
                 break;
             default:
                 if ($this->container->has($transport)) {
                     $mailer = $this->container->get($transport);
                     if ('mautic.transport.amazon' == $transport) {
                         $mailer->setHost($settings['amazon_region']);
                     }
                 }
         }
         if (method_exists($mailer, 'setMauticFactory')) {
             $mailer->setMauticFactory($this->factory);
         }
         if (!empty($mailer)) {
             if (is_callable([$mailer, 'setApiKey'])) {
                 if (empty($settings['api_key'])) {
                     $settings['api_key'] = $this->get('mautic.helper.core_parameters')->getParameter('mailer_api_key');
                 }
                 $mailer->setApiKey($settings['api_key']);
             }
             if (is_callable([$mailer, 'setUsername']) && is_callable([$mailer, 'setPassword'])) {
                 if (empty($settings['password'])) {
                     $settings['password'] = $this->get('mautic.helper.core_parameters')->getParameter('mailer_password');
                 }
                 $mailer->setUsername($settings['user']);
                 $mailer->setPassword($settings['password']);
             }
             $logger = new \Swift_Plugins_Loggers_ArrayLogger();
             $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
             try {
                 $mailer->start();
                 $translator = $this->get('translator');
                 if ($settings['send_test'] == 'true') {
                     $message = new \Swift_Message($translator->trans('mautic.email.config.mailer.transport.test_send.subject'), $translator->trans('mautic.email.config.mailer.transport.test_send.body'));
                     $userFullName = trim($user->getFirstName() . ' ' . $user->getLastName());
                     if (empty($userFullName)) {
                         $userFullName = null;
                     }
                     $message->setFrom([$settings['from_email'] => $settings['from_name']]);
                     $message->setTo([$user->getEmail() => $userFullName]);
                     $mailer->send($message);
                 }
                 $dataArray['success'] = 1;
                 $dataArray['message'] = $translator->trans('mautic.core.success');
             } catch (\Exception $e) {
                 $dataArray['message'] = $e->getMessage() . '<br />' . $logger->dump();
             }
         }
     }
     return $this->sendJsonResponse($dataArray);
 }
 function sendMail($smtp_server, $to, $from, $subject, $body, $cc, $bcc, $attachments = null, $smtp_port = 25, $smtp_username = null, $smtp_password = '', $type = 'text/plain', $transport = 0, $message_id = null, $in_reply_to = null, $inline_images = null, &$complete_mail, $att_version)
 {
     //Load in the files we'll need
     Env::useLibrary('swift');
     try {
         $mail_transport = Swift_SmtpTransport::newInstance($smtp_server, $smtp_port, $transport);
         $smtp_authenticate = $smtp_username != null;
         if ($smtp_authenticate) {
             $mail_transport->setUsername($smtp_username);
             $mail_transport->setPassword(self::ENCRYPT_DECRYPT($smtp_password));
         }
         $mailer = Swift_Mailer::newInstance($mail_transport);
         // init Swift logger
         if (defined('LOG_SWIFT') && LOG_SWIFT > 0) {
             $swift_logger = new Swift_Plugins_Loggers_ArrayLogger();
             $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($swift_logger));
             $swift_logger_level = LOG_SWIFT;
             // 0: no log, 1: log only errors, 2: log everything
         } else {
             $swift_logger_level = 0;
         }
         if (is_string($from)) {
             $pos = strrpos($from, "<");
             if ($pos !== false) {
                 $sender_name = trim(substr($from, 0, $pos));
                 $sender_address = str_replace(array("<", ">"), array("", ""), trim(substr($from, $pos, strlen($from) - 1)));
             } else {
                 $sender_name = "";
                 $sender_address = $from;
             }
             $from = array($sender_address => $sender_name);
         }
         //Create a message
         $message = Swift_Message::newInstance($subject)->setFrom($from)->setContentType($type);
         $to = self::prepareEmailAddresses($to);
         $cc = self::prepareEmailAddresses($cc);
         $bcc = self::prepareEmailAddresses($bcc);
         foreach ($to as $address) {
             $message->addTo(array_var($address, 0), array_var($address, 1, ""));
         }
         foreach ($cc as $address) {
             $message->addCc(array_var($address, 0), array_var($address, 1, ""));
         }
         foreach ($bcc as $address) {
             $message->addBcc(array_var($address, 0), array_var($address, 1, ""));
         }
         if ($in_reply_to) {
             if (str_starts_with($in_reply_to, "<")) {
                 $in_reply_to = substr($in_reply_to, 1, -1);
             }
             $validator = new SwiftHeaderValidator();
             if ($validator->validate_id_header_value($in_reply_to)) {
                 $message->getHeaders()->addIdHeader("In-Reply-To", $in_reply_to);
             }
         }
         if ($message_id) {
             if (str_starts_with($message_id, "<")) {
                 $message_id = substr($message_id, 1, -1);
             }
             $message->setId($message_id);
         }
         // add attachments
         if (is_array($attachments)) {
             foreach ($attachments as $att) {
                 if ($att_version < 2) {
                     $swift_att = Swift_Attachment::newInstance($att["data"], $att["name"], $att["type"]);
                 } else {
                     $swift_att = Swift_Attachment::fromPath($att['path'], $att['type']);
                     $swift_att->setFilename($att["name"]);
                 }
                 if (substr($att['name'], -4) == '.eml') {
                     $swift_att->setEncoder(Swift_Encoding::get7BitEncoding());
                     $swift_att->setContentType('message/rfc822');
                 }
                 $message->attach($swift_att);
             }
         }
         // add inline images
         if (is_array($inline_images)) {
             foreach ($inline_images as $image_url => $image_path) {
                 $cid = $message->embed(Swift_Image::fromPath($image_path));
                 $body = str_replace($image_url, $cid, $body);
             }
         }
         self::adjustBody($message, $type, $body);
         $message->setBody($body);
         //Send the message
         $complete_mail = self::retrieve_original_mail_code($message);
         $result = $mailer->send($message);
         if ($swift_logger_level >= 2 || $swift_logger_level > 0 && !$result) {
             file_put_contents(CACHE_DIR . "/swift_log.txt", "\n" . gmdate("Y-m-d H:i:s") . " DEBUG:\n" . $swift_logger->dump() . "----------------------------------------------------------------------------", FILE_APPEND);
             $swift_logger->clear();
         }
         return $result;
     } catch (Exception $e) {
         Logger::log("ERROR SENDING EMAIL: " . $e->getTraceAsString(), Logger::ERROR);
         //if there is an error with the connection, let the user know about it
         $mail_error = $e->getMessage();
         $mail_error = stristr($mail_error, 'Log data:', true);
         flash_error(lang('mail not sent') . " '" . $mail_error . "'");
         if ($swift_logger_level > 0) {
             $dump = $swift_logger->dump();
             if ($dump != '') {
                 file_put_contents(CACHE_DIR . "/swift_log.txt", "\n" . gmdate("Y-m-d H:i:s") . " DEBUG:\n" . $dump . "----------------------------------------------------------------------------", FILE_APPEND);
                 $swift_logger->clear();
             }
         }
         throw $e;
     }
 }
示例#12
0
 public function testAction($renderedTemplate, $toEmail)
 {
     $mailLogger = new \Swift_Plugins_Loggers_ArrayLogger();
     $this->mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($mailLogger));
     $renderedLines = explode("\n", trim($renderedTemplate));
     $subject = "Charlestown - " . $renderedLines[0];
     $body = implode("\n", array_slice($renderedLines, 1));
     $message = \Swift_Message::newInstance()->setSubject('Hello')->setFrom('*****@*****.**')->setTo($toEmail)->setBody('<html>' . ' <head></head>' . ' <body>' . $body . ' </body>' . '</html>', 'text/html');
     if ($this->mailer->send($message)) {
         echo '[SWIFTMAILER] sent email to ' . $toEmail;
     } else {
         echo '[SWIFTMAILER] not sending email: ' . $mailLogger->dump();
     }
 }
         throw new Exception($stmt2->errno . ' ' . $stmt2->error . '<br/>There was an error submitting this request.  Please click the back button and try again.');
         exit;
     }
 }
 //end of prepared statement
 // ========================================================================================
 // CREATE AND SEND EMAIL
 // ========================================================================================
 //CREATE EMAIL CONTENT
 include_once './includes/email.php';
 $email_msg = $email_start . $email_body . $biz_mgr_approval_link . $email_end;
 //SEND EMAIL TO BUSINESS MANAGER USING SWIFT MAILER
 //Create the Mailer using SMTP Transport
 $mailer = Swift_Mailer::newInstance(Swift_SmtpTransport::newInstance('smtp-gw.rochester.edu'));
 //Create Error Logger
 $logger = new Swift_Plugins_Loggers_ArrayLogger();
 $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
 // ====================================================================================
 // EMAIL TO BUSINESS MANAGER
 // ====================================================================================
 // CREATE MESSAGE
 $swift_msg = Swift_Message::newInstance("Requires Approval: Additional Pay");
 $swift_msg->setFrom('*****@*****.**');
 $swift_msg->setTo($return_path);
 if ($bcc != '') {
     $swift->setBcc($bcc);
 }
 $swift_msg->setBody($email_msg, 'text/html');
 $swift_msg->setReturnPath($return_path);
 // ECHO HEADERS FOR TROUBLESHOOTING
 /*
示例#14
0
     $domain_parts = explode("@", $current_target_email_address);
     $domain = $domain_parts[1];
     //get MX record for the destination
     getmxrr($domain, $mxhosts);
     //
     //create the transport
     if (isset($ssl) && $ssl == "no") {
         $transport = Swift_SmtpTransport::newInstance($mxhosts[0], 25);
     } else {
         $transport = Swift_SmtpTransport::newInstance($mxhosts[0], 25, 'tls');
     }
 }
 //Create the Mailer using your created Transport
 $mailer = Swift_Mailer::newInstance($transport);
 //To use the ArrayLogger
 $logger = new Swift_Plugins_Loggers_ArrayLogger();
 $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
 //Create a message
 $message = Swift_Message::newInstance($subject)->setSubject($subject)->setFrom(array($sender_email => $sender_friendly))->setReplyTo($reply_to)->setTo(array($current_target_email_address => $fname . ' ' . $lname))->setContentType($content_type)->setBody($message);
 //specify that the message has been attempted
 mysql_query("UPDATE campaigns_responses SET sent = 1 WHERE response_id = '{$current_response_id}'");
 //Send the message
 $mailer->send($message, $failures);
 //store logs in database
 $mail_log = $logger->dump();
 $mail_log = nl2br(htmlentities($mail_log));
 mysql_query("UPDATE campaigns_responses SET response_log='{$mail_log}' WHERE response_id = '{$current_response_id}'");
 //get current datetime
 $sent_time = date('Y-m-d H:i:s');
 //specify that message is sent and timestamp it
 mysql_query("UPDATE campaigns_responses SET sent = 2, sent_time = '{$sent_time}' WHERE response_id = '{$current_response_id}'");
<?php

/**
 * 330-plugin-logger-array.php
 */
require_once '../vendor/autoload.php';
require_once './config.php';
$transport = Swift_SmtpTransport::newInstance(SMTP_HOST, SMTP_PORT);
$mailer = Swift_Mailer::newInstance($transport);
// POINT of this sample
// store log to array
$logger = new Swift_Plugins_Loggers_ArrayLogger();
$mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
$message = Swift_Message::newInstance();
$message->setFrom(MAIL_FROM)->setSubject('Logger Plugin sample')->setBody('This is a mail.');
$recipients = [MAIL_TO, MAIL_TO2];
foreach ($recipients as $recipient) {
    $message->setTo($recipient);
    $result = $mailer->send($message);
}
echo $logger->dump();
示例#16
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $mailspool_id = $input->getArgument('id');
     /** @var EntityManager $em */
     $em = $this->getContainer()->get('doctrine')->getManager('default');
     $em->getFilters()->disable('tenant_filter');
     $repository = $em->getRepository('XxamMailclientBundle:Mailspool');
     $query = $repository->createQueryBuilder('s');
     $timezone = new \DateTimeZone('UTC');
     $nowutc = new \DateTime('now');
     $nowutc->setTimezone($timezone);
     if ($mailspool_id) {
         $query->where('s.id = :id');
         $query->setParameter('id', $mailspool_id);
     } else {
         $query->where('s.sendtime IS NULL AND s.sendafter <= :timenow AND s.sendstatus < 3');
         $query->setParameter('timenow', $nowutc);
     }
     /** @var mailspool[] $mailspools */
     $mailspools = $query->getQuery()->execute();
     $output->writeln('<info>Found ' . count($mailspools) . ' Mails to send...</info>' . "\n");
     foreach ($mailspools as $mailspool) {
         $output->writeln('<info>Id:</info> ' . $mailspool->getId() . "\n");
         $mailaccount = $mailspool->getMailaccount();
         $mailer = $this->getMailerForMailaccount($mailaccount);
         $logger = new \Swift_Plugins_Loggers_ArrayLogger();
         $mailer->registerPlugin(new \Swift_Plugins_LoggerPlugin($logger));
         /** @var \Swift_Message $message */
         $message = $mailspool->getMessage();
         $error = false;
         try {
             $mailer->send($message, $failures);
         } catch (\Swift_TransportException $e) {
             // Catch exceptions of type Swift_TransportException
             $output->writeln('<error>Unable to send mail (swift): ' . date("Y-m-d H:i:s") . ' - ' . $e->getMessage() . '</error> ' . "\n");
             $error = true;
         } catch (\Exception $e) {
             // Catch default PHP exceptions
             $output->writeln('<error>Unable to send mail</error> ' . "\n");
             $error = true;
         }
         $output->writeln($logger->dump());
         $mailspool->setSendlog($logger->dump());
         $mailspool->setSendstatus($mailspool->getSendstatus() + 1);
         if ($error === false) {
             $mailspool->setSendtime(new \DateTime('now'));
             //move into sent folder:
             $msg = $message->toString();
             //  (this creates the full MIME message required for imap_append()!!
             //  After this you can call imap_append like this:
             $folder = ltrim($mailaccount->getSentfolder(), '.');
             $mailbox = $this->getImapMailbox($mailaccount, $folder);
             $mailbox->addMail($msg, true);
         } else {
             $sendafter = new \DateTime($mailspool->getSendafter()->format('Y-m-d H:i:s'));
             if ($mailspool->getSendstatus() == 1) {
                 //try again in 5 minutes:
                 $sendafter->add(new \DateInterval('PT5M'));
             } else {
                 if ($mailspool->getSendstatus() == 2) {
                     //try again in 30 minutes:
                     $sendafter->add(new \DateInterval('PT30M'));
                 }
             }
             $mailspool->setSendafter($sendafter);
         }
         $em->persist($mailspool);
         $em->flush($mailspool);
     }
     $returntext = "";
     //"\n<error>ok</error>";
     $output->writeln($returntext);
 }