Exemplo n.º 1
0
 function convertToMessage($msg)
 {
     $message = new Message();
     $message->setId($msg['id']);
     $message->setDate($msg['sent_date']);
     $message->setFrom($msg['msg_from']);
     $message->setMessage($msg['message']);
     $message->setSubject($msg['subject']);
     return $message;
 }
Exemplo n.º 2
0
 function testCanSend()
 {
     $sender = $this->getMock('Evan\\Email\\ElggSender', array('send_'));
     $from = '*****@*****.**';
     $to = '*****@*****.**';
     $subject = 'Subject';
     $body = 'Body';
     $message = new Message();
     $message->setFrom($from)->setTo($to)->setSubject($subject)->setBody($body);
     $sender->expects($this->once())->method('send_')->with($from, $to, $subject, $body)->will($this->returnValue(true));
     $this->assertTrue($sender->send($message));
 }
 /**
  * Sends a single sms
  *
  * @return mixed
  */
 public function sendSms($message, $number)
 {
     try {
         $smsghMessage = new \Message();
         $smsghMessage->setContent($message);
         $smsghMessage->setTo($number);
         $smsghMessage->setFrom($this->getSenderName());
         $smsghMessage->setRegisteredDelivery(true);
         $messageResponse = $this->getApiMessage()->sendMessage($smsghMessage);
         if ($messageResponse instanceof \MessageResponse) {
             echo $messageResponse->getStatus();
         } elseif ($messageResponse instanceof \HttpResponse) {
             echo "\nServer Response Status : " . $messageResponse->getStatus();
         }
     } catch (\Exception $ex) {
         dd($ex);
     }
 }
Exemplo n.º 4
0
	/**
	 * @param $userid
	 * @param $headers
	 * @param $table_csv
	 * @param array $fields
	 * @param $parent_chkd_flds
	 * @param $export_file_name
	 * @param $debug
	 * @param null $comment
	 * @param array $to
	 */
	public static function do_sendit($userid, $headers, $table_csv, $fields = array(), $parent_chkd_flds, $export_file_name, $comment = null, $to = array(), $debug)
	{
		global $project_id, $user_rights, $app_title, $lang, $redcap_version; // we could use the global $userid, but we need control of it for setting the user as [CRON], so this is passed in args.
		$return_val = false;
		$export_type = 0; // this puts all files generated here in the Data Export category in the File Repository
		$today = date("Y-m-d_Hi"); //get today for filename
		$projTitleShort = substr(str_replace(" ", "", ucwords(preg_replace("/[^a-zA-Z0-9 ]/", "", html_entity_decode($app_title, ENT_QUOTES)))), 0, 20); // shortened project title for filename
		$originalFilename = $projTitleShort . "_" . $export_file_name . "_DATA_" . $today . ".csv"; // name the file for storage
		$today = date("Y-m-d-H-i-s"); // get today for comment, subsequent processing as needed
		$docs_comment_WH = $export_type ? "Data export file created by $userid on $today" : fix_case($export_file_name) . " file created by $userid on $today. $comment"; // unused, but I keep it around just in case
		/**
		 * setup vars for value export logging
		 */
		$chkd_fields = implode(',', $fields);
		/**
		 * turn on/off exporting per user rights
		 */
		if (($user_rights['data_export_tool'] || $userid == '[CRON]') && !$debug) {
			$table_csv = addBOMtoUTF8($headers . $table_csv);
			/**
			 * Store the file in the file system and log the activity, handle if error
			 */
			if (!DataExport::storeExportFile($originalFilename, $table_csv, true)) {
				log_event("", "redcap_data", "data_export", "", str_replace("'", "", $chkd_fields) . (($parent_chkd_flds == "") ? "" : ", " . str_replace("'", "", $parent_chkd_flds)), "Data Export Failed");
			} else {
				log_event("", "redcap_data", "data_export", "", str_replace("'", "", $chkd_fields) . (($parent_chkd_flds == "") ? "" : ", " . str_replace("'", "", $parent_chkd_flds)), "Export data for SendIt");
				/**
				 * email file link and download password in two separate emails via REDCap SendIt
				 */
				$file_info_sql = db_query("SELECT docs_id, docs_size, docs_type FROM redcap_docs WHERE project_id = $project_id ORDER BY docs_id DESC LIMIT 1"); // get required info about the file we just created
				if ($file_info_sql) {
					$docs_id = db_result($file_info_sql, 0, 'docs_id');
					$docs_size = db_result($file_info_sql, 0, 'docs_size');
					$docs_type = db_result($file_info_sql, 0, 'docs_type');
				}
				$yourName = 'PRIORITIZE REDCap';
				$expireDays = 3; // set the SendIt to expire in this many days
				/**
				 * $file_location:
				 * 1 = ephemeral, will be deleted on $expireDate
				 * 2 = export file, visible only to rights in file repository
				 */
				$file_location = 2;
				$send = 1; // always send download confirmation
				$expireDate = date('Y-m-d H:i:s', strtotime("+$expireDays days"));
				$expireYear = substr($expireDate, 0, 4);
				$expireMonth = substr($expireDate, 5, 2);
				$expireDay = substr($expireDate, 8, 2);
				$expireHour = substr($expireDate, 11, 2);
				$expireMin = substr($expireDate, 14, 2);

				// Add entry to sendit_docs table
				$query = "INSERT INTO redcap_sendit_docs (doc_name, doc_orig_name, doc_type, doc_size, send_confirmation, expire_date, username,
					location, docs_id, date_added)
				  VALUES ('$originalFilename', '" . prep($originalFilename) . "', '$docs_type', '$docs_size', $send, '$expireDate', '" . prep($userid) . "',
					$file_location, $docs_id, '" . NOW . "')";
				db_query($query);
				$newId = db_insert_id();

				$logDescrip = "Send file from file repository (Send-It)";
				log_event($query, "redcap_sendit_docs", "MANAGE", $newId, "document_id = $newId", $logDescrip);

				// Set email subject
				$subject = "[PRIORITIZE] " . $comment;
				$subject = html_entity_decode($subject, ENT_QUOTES);

				// Set email From address
				$from = array('Ken Bergquist' => '*****@*****.**');

				// Begin set up of email to send to recipients
				$email = new Message();
				foreach ($from as $name => $address) {
					$email->setFrom($address);
					$email->setFromName($name);
				}
				$email->setSubject($subject);

				// Loop through each recipient and send email
				foreach ($to as $name => $address) {
					// If a non-blank email address
					if (trim($address) != '') {
						// create key for unique url
						$key = strtoupper(substr(uniqid(md5(mt_rand())), 0, 25));

						// create password
						$pwd = generateRandomHash(8, false, true);

						$query = "INSERT INTO redcap_sendit_recipients (email_address, sent_confirmation, download_date, download_count, document_id, guid, pwd)
						  VALUES ('$address', 0, NULL, 0, $newId, '$key', '" . md5($pwd) . "')";
						$q = db_query($query);

						// Download URL
						$url = APP_PATH_WEBROOT_FULL . 'redcap_v' . $redcap_version . '/SendIt/download.php?' . $key;

						// Message from sender
						$note = "$comment for $today";
						// Get YMD timestamp of the file's expiration time
						$expireTimestamp = date('Y-m-d H:i:s', mktime($expireHour, $expireMin, 0, $expireMonth, $expireDay, $expireYear));

						// Email body
						$body = "<html><body style=\"font-family:Arial;font-size:10pt;\">
							$yourName {$lang['sendit_51']} \"$originalFilename\" {$lang['sendit_52']} " .
							date('l', mktime($expireHour, $expireMin, 0, $expireMonth, $expireDay, $expireYear)) . ",
							" . DateTimeRC::format_ts_from_ymd($expireTimestamp) . "{$lang['period']}
							{$lang['sendit_53']}<br><br>
							{$lang['sendit_54']}<br>
							<a href=\"$url\">$url</a><br><br>
							$note
							<br>-----------------------------------------------<br>
							{$lang['sendit_55']} " . CONSORTIUM_WEBSITE_DOMAIN . ".
							</body></html>";

						// Construct email and send
						$email->setTo($address);
						$email->setToName($name);
						$email->setBody($body);
						if ($email->send()) {
							// Now send follow-up email containing password
							$bodypass = "******"font-family:Arial;font-size:10pt;\">
								{$lang['sendit_50']}<br><br>
								$pwd<br><br>
								</body></html>";
							$email->setSubject("Re: $subject");
							$email->setBody($bodypass);
							sleep(2); // Hold for a second so that second email somehow doesn't reach the user first
							$email->send();
						} else {
							error_log("ERROR: pid=$project_id: Email to $name <$address> NOT SENT");
						}

					}
				}
			}
			unset($table_csv);
		}
	}
Exemplo n.º 5
0
<?php

require_once 'autoload.php';
include 'checksession.php';
if (!checksession()) {
    header('Location: login.php');
}
if (isset($_POST['message'])) {
    $msg = new Message();
    $msg->setFrom($_SESSION['operatorid']);
    $msg->setMessage($_POST['message']);
    $msg->sendMessagesTo($_POST['opid']);
    if ($_FILES['mfile']['size'][0] > 0) {
        ///put all files held in $_FILE[mfile] in to a new array $new_arr
        $new_arr = array();
        $files = $_FILES['mfile'];
        $num = count($files["name"]);
        for ($i = 0; $i < $num; $i++) {
            $new_arr[$i] = array();
        }
        foreach ($files as $key => $row) {
            for ($i = 0; $i < $num; $i++) {
                $new_arr[$i][$key] = $files[$key][$i];
            }
        }
        ///create a new upload object and upload each file
        foreach ($new_arr as $key => $value) {
            $params['upload_path'] = 'messages/';
            $params['max_file_size'] = 1000000;
            $params['linkid'] = $msg->getLinkID();
            $params['tablename'] = 'Message_Image';
Exemplo n.º 6
0
Arquivo: email.php Projeto: nob/joi
 /**
  * Send an email using a Transactional email service
  * or native PHP as a fallback.
  *
  * @param array  $attributes  A list of attributes for sending
  * @return bool on success
  */
 public static function send($attributes = array())
 {
     /*
     |--------------------------------------------------------------------------
     | Required attributes
     |--------------------------------------------------------------------------
     |
     | We first need to ensure we have the minimum fields necessary to send
     | an email.
     |
     */
     $required = array_intersect_key($attributes, array_flip(self::$required));
     if (count($required) >= 3) {
         /*
         |--------------------------------------------------------------------------
         | Load handler from config
         |--------------------------------------------------------------------------
         |
         | We check the passed data for a mailer + key first, and then fall back
         | to the global Statamic config.
         |
         */
         $email_handler = array_get($attributes, 'email_handler', Config::get('email_handler', null));
         $email_handler_key = array_get($attributes, 'email_handler_key', Config::get('email_handler_key', null));
         if (in_array($email_handler, self::$email_handlers) && $email_handler_key) {
             /*
             |--------------------------------------------------------------------------
             | Initialize Stampie
             |--------------------------------------------------------------------------
             |
             | Stampie provides numerous adapters for popular email handlers, such as
             | Mandrill, Postmark, and SendGrid. Each is written as an abstract
             | interface in an Adapter Pattern.
             |
             */
             $mailer = self::initializeEmailHandler($email_handler, $email_handler_key);
             /*
             |--------------------------------------------------------------------------
             | Initialize Message class
             |--------------------------------------------------------------------------
             |
             | The message class is an implementation of the Stampie MessageInterface
             |
             */
             $email = new Message($attributes['to']);
             /*
             |--------------------------------------------------------------------------
             | Set email attributes
             |--------------------------------------------------------------------------
             |
             | I hardly think this requires much explanation.
             |
             */
             $email->setFrom($attributes['from']);
             $email->setSubject($attributes['subject']);
             if (isset($attributes['text'])) {
                 $email->setText($attributes['text']);
             }
             if (isset($attributes['html'])) {
                 $email->setHtml($attributes['html']);
             }
             if (isset($attributes['cc'])) {
                 $email->setCc($attributes['cc']);
             }
             if (isset($attributes['bcc'])) {
                 $email->setBcc($attributes['bcc']);
             }
             if (isset($attributes['headers'])) {
                 $email->setHeaders($attributes['headers']);
             }
             $mailer->send($email);
             return true;
         } else {
             /*
             |--------------------------------------------------------------------------
             | Native PHP Mail
             |--------------------------------------------------------------------------
             |
             | We're utilizing the popular PHPMailer class to handle the messy
             | email headers and do-dads. Emailing from PHP in general isn't the best
             | idea known to man, so this is really a lackluster fallback.
             |
             */
             $email = new PHPMailer(true);
             $email->IsMAIL();
             $email->CharSet = 'UTF-8';
             $email->AddAddress($attributes['to']);
             $email->From = $attributes['from'];
             $email->FromName = $attributes['from'];
             $email->Subject = $attributes['subject'];
             if (isset($attributes['text'])) {
                 $email->AltBody = $attributes['text'];
             }
             if (isset($attributes['html'])) {
                 $email->Body = $attributes['html'];
                 $email->IsHTML(true);
             }
             if (isset($attributes['cc'])) {
                 $email->AddCC($attributes['cc']);
             }
             if (isset($attributes['bcc'])) {
                 $email->AddBCC($attributes['bcc']);
             }
             if ($email->Send()) {
                 return true;
             }
         }
     }
     return false;
 }
Exemplo n.º 7
0
<?php

// Let us test the SDK
require './Smsgh/Api.php';
$auth = new BasicAuth("user123", "password123");
// instance of ApiHost
$apiHost = new ApiHost($auth);
// instance of AccountApi
$accountApi = new AccountApi($apiHost);
// Get the account profile
// Let us try to send some message
$messagingApi = new MessagingApi($apiHost);
try {
    // Send a quick message
    $messageResponse = $messagingApi->sendQuickMessage("Husby", "+2332432191768", "I love you dearly Honey. See you in the evening...");
    $mesg = new Message();
    $mesg->setContent("I will eat the beautiful Food you have");
    $mesg->setTo("+233244219234");
    $mesg->setFrom("+233204567867");
    $mesg->setRegisteredDelivery(true);
    // Let us say we want to send the message 3 days from today
    $mesg->setTime(date('Y-m-d H:i:s', strtotime('+1 week')));
    $messageResponse = $messagingApi->sendMessage($mesg);
    if ($messageResponse instanceof MessageResponse) {
        echo $messageResponse->getStatus();
    } elseif ($messageResponse instanceof HttpResponse) {
        echo "\nServer Response Status : " . $messageResponse->getStatus();
    }
} catch (Exception $ex) {
    echo $ex->getTraceAsString();
}
Exemplo n.º 8
0
				</search-box>
		</module>
    	
		
       <module>
            
			            <select ref="msgids" model="messages" appearance="placard">
<?php 
for ($i = 0; $i < 10 && $current_page * 10 + $i < $num_messages; $i++) {
    $message = new Message();
    $current_message = $num_messages - ($current_page * 10 + $i);
    $message_uid = imap_uid($mbox, $current_message);
    $headers = imap_headerinfo($mbox, $current_message);
    $from = $headers->from[0]->personal ? $headers->from[0]->personal : $headers->from[0]->mailbox;
    $message->setFrom($from);
    $fromBlock = "<span class=\"subdued\">" . htmlspecialchars($message->getFrom()) . "</span>";
    if ($headers->Unseen == 'U') {
        //Not read
        $fromBlock = "<strong>" . htmlspecialchars($message->getFrom()) . "</strong>";
    }
    $message->setSubject($headers->subject);
    $date = strtotime($headers->date);
    $now = time();
    $minutes_between = ($now - $date) / 60;
    if ($minutes_between < 60) {
        $display_date = round(($now - $date) / 60) . 'm ago';
    } else {
        if ($minutes_between < 60 * 24) {
            $display_date = date('g:i a', $date);
        } else {
Exemplo n.º 9
0
 public function sendMessage()
 {
     if (isset($_POST['send-msg'])) {
         $to = $_POST['msgTo'];
         $msg = new Message();
         $msg->setTo($to);
         $currentUser = wp_get_current_user();
         $msg->setFrom($currentUser->ID);
         $msg->setSubject($_POST['subject']);
         $msg->setMessage($_POST['message']);
         $msg->send();
         $this->redirect(admin_url('admin.php?page=vmp-msgs'));
     }
 }
Exemplo n.º 10
0
 /**
  * Creates a new message instance.
  *
  * @return Message
  */
 public function createMessage()
 {
     $message = new Message();
     $message->setFrom($this->from);
     return $message;
 }
Exemplo n.º 11
0
//$auth = new BasicAuth("yralkzfn", "znbzlsho");
$auth = new BasicAuth("obxffxqt", "wmqimxzt");
// instance of ApiHost
$apiHost = new ApiHost($auth);
// instance of AccountApi
$accountApi = new AccountApi($apiHost);
// Get the account profile
// Let us try to send some message
$messagingApi = new MessagingApi($apiHost);
try {
    // Send a quick message
    //$messageResponse = $messagingApi->sendQuickMessage("Husby", "+2332432191768", "I love you dearly Honey. See you in the evening...");
    $mesg = new Message();
    $mesg->setContent($newMessage);
    $mesg->setTo($customer);
    $mesg->setFrom("+233543344100");
    $mesg->setRegisteredDelivery(true);
    // Let us say we want to send the message 3 days from today
    //$mesg->setTime(date('Y-m-d H:i:s', strtotime('+1 week')));
    $messageResponse = $messagingApi->sendMessage($mesg);
    if ($messageResponse instanceof MessageResponse) {
        echo '{"result": 1, "message": "' . $messageResponse->getStatus() . '"}';
        return;
        //echo $messageResponse->getStatus();
    } elseif ($messageResponse instanceof HttpResponse) {
        echo '{"result": 0, "message": "' . $messageResponse->getStatus() . '"}';
        return;
        // echo "\nServer Response Status : " . $messageResponse->getStatus();
    }
} catch (Exception $ex) {
    echo $ex->getTraceAsString();
Exemplo n.º 12
0
 public function parseMessage($messageObject)
 {
     $message = new Message();
     $message->setMessageId($messageObject->message_id);
     $message->setFrom($this->parseUser($messageObject->from));
     $message->setDate($messageObject->date);
     // TODO: test it for User and GroupChat types
     $message->setChat($this->parseChat($messageObject->chat));
     if (property_exists($messageObject, 'forward_from')) {
         $message->setForwardFrom($this->parseUser($messageObject->forward_from));
     }
     if (property_exists($messageObject, 'forward_date')) {
         $message->setForwardDate($messageObject->forward_date);
     }
     // TODO: reply to message attribute
     if (property_exists($messageObject, 'text')) {
         $message->setText($messageObject->text);
     }
     if (property_exists($messageObject, 'audio')) {
         $message->setAudio($this->parseAudio($messageObject->audio));
     }
     if (property_exists($messageObject, 'document')) {
         $message->setDocument($this->parseDocument($messageObject->document));
     }
     if (property_exists($messageObject, 'photo')) {
         $message->setPhoto($this->parsePhotoSize($messageObject->photo));
     }
     if (property_exists($messageObject, 'sticker')) {
         $message->setSticker($this->parseSticker($messageObject->sticker));
     }
     if (property_exists($messageObject, 'video')) {
         $message->setVideo($this->parseVideo($messageObject->video));
     }
     if (property_exists($messageObject, 'voice')) {
         $message->setVoice($this->parseVoice($messageObject->voice));
     }
     if (property_exists($messageObject, 'caption')) {
         $message->setCaption($messageObject->caption);
     }
     if (property_exists($messageObject, 'contact')) {
         $message->setContact($this->parseContact($messageObject->contact));
     }
     if (property_exists($messageObject, 'location')) {
         $message->setLocation($this->parseLocation($messageObject->location));
     }
     if (property_exists($messageObject, 'new_chat_participant')) {
         $message->setNewChatParticipant($this->parseUser($messageObject->new_chat_participant));
     }
     if (property_exists($messageObject, 'left_chat_participant')) {
         $message->setLeftChatParticipant($this->parseUser($messageObject->left_chat_participant));
     }
     if (property_exists($messageObject, 'new_chat_title')) {
         $message->setNewChatTitle($messageObject->new_chat_title);
     }
     if (property_exists($messageObject, 'new_chat_photo')) {
         $message->setNewChatPhoto($this->parsePhotoSize($messageObject->new_chat_photo));
     }
     // TODO: not sure about implementation of TRUE type
     if (property_exists($messageObject, 'delete_chat_photo')) {
         $message->setDeleteChatPhoto($messageObject->delete_chat_photo);
     }
     if (property_exists($messageObject, 'group_chat_created')) {
         $message->setGroupChatCreated($messageObject->group_chat_created);
     }
     return $message;
 }
Exemplo n.º 13
0
 /**
  * Creating a instance of this
  *
  * @param string  $from
  * @param string  $to
  * @param string  $subject
  * @param string  $body
  * @param string  $type
  * @param string  $status
  *
  * @return Message
  */
 public static function create($from, $to, $subject, $body, $type, $attachmentAssets = array())
 {
     $attacheAssetIds = array();
     foreach ($attachmentAssets as $asset) {
         if ($asset instanceof Asset) {
             $attacheAssetIds[] = trim($asset->getAssetId());
         }
     }
     $entity = new Message();
     return $entity->setFrom(trim($from))->setTo(trim($to))->setSubject(trim($subject))->setBody(trim($body))->setType(trim($type))->setAttachAssetIds(implode(',', $attacheAssetIds))->save();
 }
Exemplo n.º 14
0
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
    $pageNumber = $_GET['page'];
} else {
    $pageNumber = 0;
}
$total_messages = imap_num_msg($mbox);
$charset = 'UTF-8';
$structure = imap_fetchstructure($mbox, $msg_number);
foreach ($structure->parameters as $param) {
    if ($param->attribute == 'charset') {
        $charset = $param->value;
        break;
    }
}
$header = imap_headerinfo($mbox, $msg_number);
$message->setFrom($header->fromaddress);
$message->setTo($header->toaddress);
$message->setCc($header->ccaddress);
$message->setSubject($header->subject);
$message->setBody(imap_fetchbody($mbox, $msg_number, '1'));
// '1' is the text/plain version of the body in a multipart message
$message->setDate($header->date);
$_SESSION['currentMessage'] = serialize($message);
if ($msg_number > 1) {
    $prev_message = imap_uid($mbox, $msg_number - 1);
} else {
    $prev_message = null;
}
if ($msg_number < $total_messages) {
    $next_message = imap_uid($mbox, $msg_number + 1);
} else {
Exemplo n.º 15
0
    /**
     * Send an email using a Transactional email service
     * or native PHP as a fallback.
     *
     * @param array  $attributes  A list of attributes for sending
     * @return bool on success
     */
    public static function send($attributes = array())
    {
        /*
        |--------------------------------------------------------------------------
        | Required attributes
        |--------------------------------------------------------------------------
        |
        | We first need to ensure we have the minimum fields necessary to send
        | an email.
        |
        */
        $required = array_intersect_key($attributes, array_flip(self::$required));

        if (count($required) >= 3) {

            /*
            |--------------------------------------------------------------------------
            | Load handler from config
            |--------------------------------------------------------------------------
            |
            | We check the passed data for a mailer + key first, and then fall back
            | to the global Statamic config.
            |
            */
            $email_handler     = array_get($attributes, 'email_handler', Config::get('email_handler', null));
            $email_handler_key = array_get($attributes, 'email_handler_key', Config::get('email_handler_key', null));

            if (in_array($email_handler, self::$email_handlers) && $email_handler_key) {

                /*
                |--------------------------------------------------------------------------
                | Initialize Stampie
                |--------------------------------------------------------------------------
                |
                | Stampie provides numerous adapters for popular email handlers, such as
                | Mandrill, Postmark, and SendGrid. Each is written as an abstract
                | interface in an Adapter Pattern.
                |
                */
                $mailer = self::initializeEmailHandler($email_handler, $email_handler_key);

                /*
                |--------------------------------------------------------------------------
                | Initialize Message class
                |--------------------------------------------------------------------------
                |
                | The message class is an implementation of the Stampie MessageInterface
                |
                */
                $email = new Message($attributes['to']);

                /*
                |--------------------------------------------------------------------------
                | Set email attributes
                |--------------------------------------------------------------------------
                |
                | I hardly think this requires much explanation.
                |
                */
                $email->setFrom($attributes['from']);

                $email->setSubject($attributes['subject']);

                if (isset($attributes['text'])) {
                    $email->setText($attributes['text']);
                }

                if (isset($attributes['html'])) {
                    $email->setHtml($attributes['html']);
                }

                if (isset($attributes['cc'])) {
                    $email->setCc($attributes['cc']);
                }

                if (isset($attributes['bcc'])) {
                    $email->setBcc($attributes['bcc']);
                }

                if (isset($attributes['headers'])) {
                    $email->setHeaders($attributes['headers']);
                }

                $mailer->send($email);

                return true;

            } else {

                /*
                |--------------------------------------------------------------------------
                | Native PHP Mail
                |--------------------------------------------------------------------------
                |
                | We're utilizing the popular PHPMailer class to handle the messy
                | email headers and do-dads. Emailing from PHP in general isn't the best
                | idea known to man, so this is really a lackluster fallback.
                |
                */
            try {
                $email = new PHPMailer(true);

                // SMTP
                if ($attributes['smtp'] = array_get($attributes, 'smtp', Config::get('smtp'))) {
                    
                    $email->isSMTP();

                    if ($smtp_host = array_get($attributes, 'smtp:host', false)) {
                        $email->Host = $smtp_host;
                    }

                    if ($smtp_secure = array_get($attributes, 'smtp:secure', false)) {
                        $email->SMTPSecure = $smtp_secure;
                    }

                    if ($smtp_port = array_get($attributes, 'smtp:port', false)) {
                        $email->Port = $smtp_port;
                    }

                    if (array_get($attributes, 'smtp:auth', false) === TRUE) {
                        $email->SMTPAuth = TRUE;
                    }

                    if ($smtp_username = array_get($attributes, 'smtp:username', false)) {
                        $email->Username = $smtp_username;
                    }

                    if ($smtp_password = array_get($attributes, 'smtp:password', false)) {
                        $email->Password = $smtp_password;
                    }

                // SENDMAIL
                } elseif (array_get($attributes, 'sendmail', false)) {
                    $email->isSendmail();

                // PHP MAIL
                } else {
                    $email->isMail();
                }

                $email->CharSet = 'UTF-8';

                $from_parts = self::explodeEmailString($attributes['from']);
                $email->setFrom($from_parts['email'], $from_parts['name']);

                $to = Helper::ensureArray($attributes['to']);
                foreach ($to as $to_addr) {
                    $to_parts = self::explodeEmailString($to_addr);
                    $email->addAddress($to_parts['email'], $to_parts['name']);
                }

                $email->Subject  = $attributes['subject'];

                if (isset($attributes['html'])) {
                    $email->msgHTML($attributes['html']);

                    if (isset($attributes['text'])) {
                        $email->AltBody = $attributes['text'];
                    }

                } elseif (isset($attributes['text'])) {
                    $email->msgHTML($attributes['text']);
                }

                if (isset($attributes['cc'])) {
                    $cc = Helper::ensureArray($attributes['cc']);
                    foreach ($cc as $cc_addr) {
                        $cc_parts = self::explodeEmailString($cc_addr);
                        $email->addCC($cc_parts['email'], $cc_parts['name']);
                    }                    
                }

                if (isset($attributes['bcc'])) {
                    $bcc = Helper::ensureArray($attributes['bcc']);
                    foreach ($bcc as $bcc_addr) {
                        $bcc_parts = self::explodeEmailString($bcc_addr);
                        $email->addBCC($bcc_parts['email'], $bcc_parts['name']);
                    }      
                }

                $email->send();

                } catch (phpmailerException $e) {
                    echo $e->errorMessage(); //error messages from PHPMailer
                    Log::error($e->errorMessage(), 'core', 'email');
                } catch (Exception $e) {
                    echo $e->getMessage();
                    Log::error($e->getMessage(), 'core', 'email');
                }

            }
        }

        return false;
    }
Exemplo n.º 16
0
 public function notify($title)
 {
     global $redcap_version;
     $dark = "#800000";
     //#1a74ba  1a74ba
     $light = "#FFE1E1";
     //#ebf6f3
     $border = "#800000";
     //FF0000";	//#a6d1ed	#3182b9
     // Run notification
     $url = APP_PATH_WEBROOT_FULL . "redcap_v{$redcap_version}/" . "DataEntry/index.php?pid={$this->project_id}&page={$this->instrument}&id={$this->record}&event_id={$this->event_id}";
     // Message (email html painfully copied from box.net notification email)
     $msg = RCView::table(array('cellpadding' => '0', 'cellspacing' => '0', 'border' => '0', 'style' => 'border:1px solid #bbb; font:normal 12px Arial;color:#666'), RCView::tr(array(), RCView::td(array('style' => 'padding:13px'), RCView::table(array('style' => 'font:normal 15px Arial'), RCView::tr(array(), RCView::td(array('style' => 'font-size:18px;color:#000;border-bottom:1px solid #bbb'), RCView::span(array('style' => 'color:black'), RCVieW::a(array('style' => 'color:black'), 'REDCap AutoNotification Alert')) . RCView::br())) . RCView::tr(array(), RCView::td(array('style' => 'padding:10px 0'), RCView::table(array('style' => 'font:normal 12px Arial;color:#666'), RCView::tr(array(), RCView::td(array('style' => 'text-align:right'), "Title") . RCView::td(array('style' => 'padding-left:10px;color:#000'), RCView::span(array('style' => 'color:black'), RCView::a(array('style' => 'color:black'), "<b>{$title}</b>")))) . RCView::tr(array(), RCView::td(array('style' => 'text-align:right'), "Project") . RCView::td(array('style' => 'padding-left:10px;color:#000'), RCView::span(array('style' => 'color:black'), RCView::a(array('style' => 'color:black'), REDCap::getProjectTitle())))) . ($this->redcap_event_name ? RCView::tr(array(), RCView::td(array('style' => 'text-align:right'), "Event") . RCView::td(array('style' => 'padding-left:10px;color:#000'), RCView::span(array('style' => 'color:black'), RCView::a(array('style' => 'color:black'), "{$this->redcap_event_name}")))) : '') . RCView::tr(array(), RCView::td(array('style' => 'text-align:right'), "Instrument") . RCView::td(array('style' => 'padding-left:10px;color:#000'), RCView::span(array('style' => 'color:black'), RCView::a(array('style' => 'color:black'), $this->instrument)))) . RCView::tr(array(), RCView::td(array('style' => 'text-align:right'), "Record") . RCView::td(array('style' => 'padding-left:10px;color:#000'), RCView::span(array('style' => 'color:black'), RCView::a(array('style' => 'color:black'), $this->record)))) . RCView::tr(array(), RCView::td(array('style' => 'text-align:right'), "Date/Time") . RCView::td(array('style' => 'padding-left:10px;color:#000'), RCView::span(array('style' => 'color:black'), RCView::a(array('style' => 'color:black'), date('Y-m-d H:i:s'))))) . RCView::tr(array(), RCView::td(array('style' => 'text-align:right'), "Message") . RCView::td(array('style' => 'padding-left:10px;color:#000'), RCView::span(array('style' => 'color:black'), RCView::a(array('style' => 'color:black'), $this->config['message']))))))) . RCView::tr(array(), RCView::td(array('style' => "border:1px solid {$border};background-color:{$light};padding:20px"), RCView::table(array('style' => 'font:normal 12px Arial', 'cellpadding' => '0', 'cellspacing' => '0'), RCView::tr(array('style' => 'vertical-align:middle'), RCView::td(array(), RCView::table(array('cellpadding' => '0', 'cellspacing' => '0'), RCView::tr(array(), RCView::td(array('style' => "border:1px solid #600000;background-color:{$dark};padding:8px;font:bold 12px Arial"), RCView::a(array('class' => 'hide', 'style' => 'color:#fff;white-space:nowrap;text-decoration:none', 'href' => $url), "View Record"))))) . RCView::td(array('style' => 'padding-left:15px'), "To view this record, visit this link:" . RCView::br() . RCView::a(array('style' => "color:{$dark}", 'href' => $url), $url))))))))));
     $msg = "<HTML><head></head><body>" . $msg . "</body></html>";
     // Determine number of emails to send
     // Prepare message
     $email = new Message();
     $email->setTo($this->config['to']);
     $email->setFrom($this->config['from']);
     $email->setSubject($this->config['subject']);
     $email->setBody($msg);
     // Send Email
     if (!$email->send()) {
         error_log('Error sending mail: ' . $email->getSendError() . ' with ' . json_encode($email));
         exit;
     }
     //		error_log ('Email sent');
     // Add Log Entry
     $data_values = "title,{$title}\nrecord,{$this->record}\nevent,{$this->redcap_event_name}";
     REDCap::logEvent('AutoNotify Alert', $data_values);
 }
		/**
		 * set up email for sending
		 */
		$to = array(
			'Ken Bergquist' => '*****@*****.**',
			'Lasheaka McClellan' => '*****@*****.**',
			'Tyre Johnson' => '*****@*****.**',
			'Dona-Marie Mintz' => '*****@*****.**',
			'Nicholas Slater' => '*****@*****.**'
		);
		//$to = array('Ken Bergquist' => '*****@*****.**');
		$from = array('Ken Bergquist' => '*****@*****.**');
		$subject = "HCV-TARGET 2 Site Source Upload Notification";
		$email = new Message ();
		foreach ($from as $name => $address) {
			$email->setFrom($address);
			$email->setFromName($name);
		}
		$email->setSubject($subject);
		$email->setBody($html);
		foreach ($to as $name => $address) {
			$email->setTo($address);
			$email->setToName($name);
			if (!$debug) {
				if (!$email->send()) {
					error_log("ERROR: Failed to send Site Source Upload digest");
				}
			}
		}
		d($email);
	} else {
Exemplo n.º 18
0
 /**
  * send:
  *
  * @param array|string $pmTo
  *        	- Who will receve the message, array('email', 'name') or
  *        	'email'
  * @param string $psSubject
  *        	messagem subject
  * @param string $psBodyText
  *        	- message in plan text format
  * @param string $psBodyHtml
  *        	- message in html format
  * @param array|string $paFrom
  *        	- Who send the message, array('email', 'name') or 'email'
  *        	
  * @return Zend_Mail
  */
 public function send($pmFrom, $psSubject, $pmBody, $pmTo = null)
 {
     $lsFromEmail = null;
     $lsFromName = null;
     $lsToEmail = null;
     $lsToName = null;
     $loMail = new Message();
     $loMail->setEncoding($this->_aOptions['charset']);
     $loMail->setSender($this->_aOptions["fromEmail"], $this->_aOptions["fromName"]);
     $loMail->addReplyTo($this->_aOptions["replayToEmail"], $this->_aOptions["replayToName"]);
     $loMail->setSubject($psSubject);
     $loMail->setBody($this->setContainer($pmBody));
     if (is_array($pmTo)) {
         if (isset($pmTo[0])) {
             $lsToEmail = $pmTo[0];
         }
         if (isset($pmTo[1])) {
             $lsToName = $pmTo[1];
         }
     } elseif (is_string($pmTo)) {
         $lsToEmail = $pmTo;
     } else {
         $lsToEmail = $this->_aOptions["fromEmail"];
         $lsToName = $this->_aOptions["fromName"];
     }
     $loMail->addTo($lsToEmail, $lsToName);
     if (is_array($pmFrom)) {
         if (isset($pmFrom[0])) {
             $lsFromEmail = $pmFrom[0];
         }
         if (isset($pmFrom[1])) {
             $lsFromName = $pmFrom[1];
         }
     } elseif (is_string($pmFrom)) {
         $lsFromEmail = $pmFrom;
     } else {
         $lsFromEmail = $this->_aOptions["fromEmail"];
         $lsFromName = $this->_aOptions["fromName"];
     }
     $loMail->setFrom($lsFromEmail, $lsFromName);
     if ($this->_aOptions["transporter"] == "SMTP") {
         $loOptionsSMTP = new Transport\SmtpOptions($this->getSMTPOptions());
         $loTransport = new Transport\Smtp($loOptionsSMTP);
         $loTransport->send($loMail);
     } elseif ($this->_aOptions["transporter"] == "sendmail") {
         $loTransport = new Transport\Sendmail();
         $loTransport->send($loMail);
     }
 }