Skip to content

Instantly share code, notes, and snippets.

@nebiros
Created April 15, 2014 16:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebiros/10746308 to your computer and use it in GitHub Desktop.
Save nebiros/10746308 to your computer and use it in GitHub Desktop.
mailer
<?php
// Type of argument.
define("ARG_TYPE", 2);
// Argument value.
define("ARG_VALUE", 3);
// Define default mail "From:".
define("DEFAULT_EMAIL_FROM", "");
// Define array of arguments.
$defaultCliArgs = array("mails", "attach", "reply", "from", "html", "subject", "message_file", "message_text");
// Define default array of errors when we try to send a mail.
$errors = array();
<?php
/**
* Mailer.
*
* @author nebiros
*/
class Mailer {
protected $_mailsFilePath = null;
protected $_from = null;
protected $_mails = array();
protected $_subject = null;
protected $_reply = null;
protected $_message = null;
protected $_messageText = null;
protected $_messageFile = null;
protected $_attachment = null;
protected $_isXhtml = false;
protected $_headers = null;
public function __construct($args) {
// Set strMailsFile attribute.
$this->_mailsFilePath = $args["mails"];
if (true === empty($this->_mailsFilePath)) {
throw new Exception("mails argument can't be empty");
}
if (false === empty($this->_mailsFilePath) && false === is_file($this->_mailsFilePath)) {
throw new Exception("mails file should be a file! :O");
}
// Set strMailSubject attribute.
$this->_subject = $args["subject"];
if (true === empty($this->_subject)) {
throw new Exception("mail subject argument can't be empty");
}
// Set strMailFrom attribute.
$this->_from = $args["from"];
// Set strMailReply attribute.
$this->_reply = $args["reply"];
// Set strMailMessageText attribute.
$this->_messageText = $args["message_text"];
// Set strMailMessageFile attribute.
$this->_messageFile = $args["message_file"];
// If there's not message ...
if (true === empty($this->_messageText) && true === empty($this->_mailsFilePath))
{
throw new Exception("mail message argument can't be empty, please use --message_text or --message_file argument");
}
if (false === empty($this->_messageFile) && false === is_file($this->_messageFile))
{
throw new Exception("message file should be a file! :O");
}
$this->_isXhtml = (bool) $args["html"];
$this->_attachment = $args["attach"];
if (false === empty($this->_attachment) && false === is_file($this->_attachment)) {
throw new Exception("Attachment file should be a file! :O");
}
$this->_setMailData();
$this->_mails = $this->getEmails();
}
public function getEmails() {
if (true === empty($this->_mailsFilePath)) {
throw new Exception("mails file can't be empty");
}
try {
// Open file.
// $rscMailsFile = fopen($this->strMailsFile, "r");
$mails = file($this->_mailsFilePath);
} catch (Exception $e) {
throw new Exception("can't get mails from this file {$this->_mailsFilePath} - ({$e->getMessage()})");
}
return $mails;
}
protected function _setMailData() {
if (false === empty($this->_messageFile)) {
$this->_message = file_get_contents($this->_messageFile);
} else if (false === empty($this->_messageText)) {
$this->_message = $this->_messageText;
}
if (false === empty($this->_messageFile) && false === empty($this->_messageText)) {
$this->_message = $this->_messageText;
$this->_message .= file_get_contents($this->_messageFile);
}
$this->_headers = $this->_setMailHeaders();
}
protected function _setMailHeaders() {
$mailHeaders = "";
$boundaryHash = md5(date("r", time()));
if (true === empty($this->_from)) {
$this->_from = DEFAULT_EMAIL_FROM;
}
ini_set("sendmail_from", $this->_from);
$mailHeaders .= "From: {$this->_from}\r\n";
if (false === empty($this->_reply)) {
$mailHeaders .= "Reply-To: {$this->_reply}\r\n";
}
$mailHeaders .= "MIME-Version: 1.0\r\n";
if (false === empty($this->_attachment)) {
$mailHeaders .= "Content-Type: multipart/mixed; boundary=\"mixed-{$boundaryHash}\"";
} else {
$mailHeaders .= "Content-Type: multipart/alternative; boundary=\"alt-{$boundaryHash}\"";
}
$this->_setMessageWithHeaders($boundaryHash);
return $mailHeaders;
}
/**
* Set message with all the headers needed.
*
* @param string $boundaryHash Boundary hash.
* @return void
*/
protected function _setMessageWithHeaders($boundaryHash) {
ob_start();
// TODO: must be a heredoc.
// set some headers if we have a file to be attached.
if (false === empty($this->_attachment)) {
?>
--mixed-<?php echo $boundaryHash . "\n" ?>
Content-Type: multipart/alternative; boundary="alt-<?php echo $boundaryHash ?>"<?php echo "\n" ?>
<?php
}
?>
--alt-<?php echo $boundaryHash . "\n" ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<?php echo $this->_message . "\n" ?>
--alt-<?php echo $boundaryHash . "\n" ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<?php echo $this->_message . "\n" ?>
--alt-<?php echo $boundaryHash ?>--<?php echo "\n" ?>
<?php
// add attachment.
if (false === empty($this->_attachment)) {
?>
--mixed-<?php echo $boundaryHash . "\n" ?>
Content-Type: "<?php echo mime_content_type($this->_attachment) ?>"; name="<?php echo basename($this->_attachment) ?>"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; file="<?php echo basename($this->_attachment) ?>"
<?php
// encode attachment and add it to the mail message.
$attachmentEncoded = chunk_split(base64_encode(file_get_contents($this->_attachment)));
?>
<?php echo $attachmentEncoded . "\n" ?>
--mixed-<?php echo $boundaryHash ?>--
<?
}
// Now set the mail message with all headers needed :).
$this->_message = ob_get_clean();
}
/**
* Send mails :O.
*
* @return void
*/
public function sendMails() {
global $errors;
// Loop every line.
foreach ($this->_mails AS $index => $mail) {
if (false === mail($mail, $this->_subject, $this->_message, $this->_headers)) {
// NOTE: I'll do print a message when the mail can't be sent because I'm working in the CLI.
echo "==> can't send email to this recipient: {$mail}";
$errors[] = "Can't be sent mail for {$mail}";
} else {
echo "==> mail sent to {$mail}";
}
}
}
}
<?php
defined("APPLICATION_PATH")
|| define("APPLICATION_PATH", realpath(dirname(__FILE__)));
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . "/library"),
realpath(APPLICATION_PATH . "/functions"),
get_include_path(),
)));
// Set timeout.
ini_set("set_time_limit", 0);
error_reporting(E_ALL & ~E_NOTICE);
require_once "constants.php";
require_once "shared.php";
if (false === ($args = getArguments())) {
drawCliHelp();
exit();
}
function __autoload($class) {
require_once($class . ".php");
}
echo "==> starting ...\n";
$mailer = new Mailer($args);
echo "==> sending ...\n";
$mailer->sendMails();
if (false === empty($errors)) {
echo "==> error!\n";
echo implode("\n", $errors);
}
echo "==> done\n\n";
<?php
/**
* Shared functions.
*
*/
/**
* Pretty print_r
*
* @param array $data Thy array! :O
* @return string
*/
function pprint_r($data) {
$output = "";
$output .= "<pre>" . print_r($data, true) . "</pre>";
echo $output;
}
/**
*
* @param string $usFormatDate
* @return string|null
*/
function usToPostgresDateFormat($usFormatDate) {
if (true === empty($usFormatDate)) {
return null;
}
preg_match("/(\d+)\/(\d+)\/(\d+)/", $usFormatDate, $matches);
if (true === empty($matches)) {
return null;
}
return preg_replace("/(\d+)\/(\d+)\/(\d+)/", "$3-$1-$2", $usFormatDate);
}
/**
*
* @param string $postgresFormatDate
* @param bool $showTime
* @return string
*/
function postgresToUsDateFormat($postgresFormatDate, $showTime = false) {
if (true === empty($postgresFormatDate)) {
return null;
}
preg_match("/(\d+)-(\d+)-(\d+) (.+)/", $postgresFormatDate, $matches);
if (true === empty($matches)) {
return null;
}
if (false === $showTime) {
return preg_replace("/(\d+)-(\d+)-(\d+) (.+)/", "$2/$3/$1", $postgresFormatDate);
} else {
return preg_replace("/(\d+)-(\d+)-(\d+) (.+)/", "$2/$3/$1 $4", $postgresFormatDate);
}
}
/**
* Get arguments by type.
*
* @return array Array of arguments by type.
*/
function getArguments() {
global $defaultCliArgs;
$cliArgs = $_SERVER["argv"]; $args = array();
foreach ($cliArgs AS $index => $arg) {
preg_match("/^(--|-)(.+)\=(.+)/", $arg, $matches);
if (true === in_array($matches[ARG_TYPE], $defaultCliArgs)) {
if (false === empty($matches)) {
$args[$matches[ARG_TYPE]] = $matches[ARG_VALUE];
}
}
}
if (true === empty($args)) {
return false;
}
return $args;
}
/**
*
* @return string
*/
function drawCliHelp() {
$help = "";
$help .= "PHP Mailer v0.1\n\n";
$help .= "Options:\n";
$help .= "\t--mails=<MAILS_FILE> - File with all mails per line.\n";
$help .= "\t--subject=<SUBJECT_TEXT> - Mail subject.\n";
$help .= "\t--from=<FROM_EMAIL> - Mail from clause.\n";
$help .= "\t--reply=<REPLY_TO_MAIL> - Reply-To mail.\n";
$help .= "\t--message_text=<MESSAGE_TEXT> - Message to be set into the mail.\n";
$help .= "\t--message_file=<MESSAGE_FILE> - If we want to read a file with the message.\n";
$help .= "\t--html=<true|false> - If the mail will be sent as html or not.\n";
$help .= "\t--attach=<FILE_TO_ATTACH> - File to be attached to the mail.\n";
$help .= "\n";
echo $help;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment