Simple EMail PHP Script

Below is a free script to allow you to send a simple e-mail.

Sending e-mail can seem like such a trivial task that I almost debated not putting up this page – but then I figured that there are often times when we write a very sloppy and dirty script since the built in PHP mail function is so easy.  This script allows for a little bit of a cleaner approach to send an e-mail.

The script allows for a config seperation allowing you to change configuration settings between different environments such as dev, staging and production.  A test function is provided as well as function to get the in use e-mail settings – a handy and straight forward piece fo code for developers deving against a shared hosting environment that might not have access to detailed information.  The script also has a quick little logging feature built into it so that you can add several log statements throughout the code for easy debugging.

So – I hope you enjoy – I welcome and encourage any feedback or comments in the comment section.

 

<?

/**
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT
 * HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR
 * FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE
 * OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS,
 * COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.COPYRIGHT HOLDERS WILL NOT
 * BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL
 * DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://gnu.org/licenses/>.
 *
 * URL: http://www.benhallbenhall.com
 */

 /*
  * Email Class allows for a centrally managed class to send out e-mails
  * Allows for the easy override of Server settings depending on environment (dev, staging, production, etc...)
  *
  * Define the following constants in a config file if you choose to use them:
  * 	EMAIL_DEFAULT_SENDER_NAME = The Real Name of the default sender such as Business XYZ, Website Admin, etc...
  *	EMAIL_DEFAULT_SENDER_EMAIL = The Real Email address of the default sender such as support@test.com
  * 	EMAIL_DEFAULT_RECIPIENT = A default email address to send the email to (useful for internal submissions from multiple forms)
  *
  * The following defines can be set at the INI level
  * 	EMAIL_CUSTOM_SMTP_SERVER = The default SMTP server to use such as smtp.example.com
  *	EMAIL_CUSTOM_SMTP_FROM = The default Email address to send the email from such as webmaster@example.com
  */

class Email{

        public static $enableErrorLogs=true;
        /*
	 * When called creates a basic test message using the current default settings for the Email class
	 *
	 * @return passed through from the sendEmail function
	 */
	public static function emailTest(){
		return self::sendEmail();
	}

	/*
	 * Returns the current settings being used for e-mail interactions
	 *
	 * @return array of settings
	 */
	public static function getEmailSettings(){
		$settings = array();
		$settings['SMTP']=ini_get('SMTP');
		$settings['sendmail_from']=ini_get('sendmail_from');
		//Insert any additional params into the array here
		return $settings;
	}

	/*
	 * Sends an e-mail
	 *
	 * @param 	array $options		An array of options to be passed to the email program such as senders name, email address and so forth
	 */

	public static function sendEmail($options, $headers=array()){

		//Setup the default variables to use if any were not passed.
		$options=array(
			'senderName'=>'Example Name',
			'senderEmail'=>'example@example.com',
			'recipient'=>'recipient1@example.com', //or 'recipient'=>'recipient1@example.com,recipient2@example.com',
			'subject'=>'Exmaple Subject for the Email',
			'body'=>'This is the sample message body for the subject',
		);

		//Set INI variables if they are defined
		self::setIniVariables();

		//Mail Defaults
		$defaults = array();
		if(defined('EMAIL_DEFAULT_SENDER_NAME')){
			$defaults['senderName']=EMAIL_DEFAULT_SENDER_NAME;
		}
		if(defined('EMAIL_DEFAULT_SENDER_EMAIL')){
			$defaults['senderEmail']=EMAIL_DEFAULT_SENDER_EMAIL;
		}
		if(defined('EMAIL_DEFAULT_RECIPIENT')){
			$defaults['recipient']=EMAIL_DEFAULT_RECIPIENT;
		}
		$defaults['body']='Default Email Body';
		$defaults['subject']='Default Email Subject';

		//Merge the options together
		$options = array_merge($defaults, $options);

		//Headers
		$defaultHeaders=array();
		$defaultHeaders['X-Mailer']='X-Mailer: PHP/'.phpversion();
		$defaultHeaders['MIME-Version']='MIME-Version: 1.0';
		$defaultHeaders['Content-type']='Content-type: text/html; charset=iso-8859-1';

		//Merge the Headers
		$headers = array_merge($defaultHeaders, $headers);

		//Grab some default info if certain fields were not specified
		if(!array_key_exists('From',$headers)){
			$headers['From']='From: '. $options['senderName'] . ' <' . $options['senderEmail'] . '>';
		}
		if(!array_key_exists('Reply-To',$headers)){
			$headers['Reply-To']='Reply-To: '.$options['senderEmail'];
		}

		//Build the header string for inclusion in the script
		$headerString='';
		$first=true;
		foreach($headers as $key=>$value){
			if(!$first){
				$headerString.="rn";
			}
			$headerString .= $value;
			$first=false;
		}

		//Try to send the mail
		try{
			mail($options['recipient'], $options['subject'], $options['body'], $headerString);
		}catch(Exception $e){
			self::l('Mail Send Error (will try once more): '.$e->getMessage());
			//Try it again without the Headers...
			try{
				mail($options['recipient'], $options['subject'], $options['body']);
			}catch(Exception $e){
				self::l('Mail Re-Try Send Error (Quiting this time): '.$e->getMessage());
			}
		} 

	}

	/*
	 * Set certain constants into the INI settings if defined
	 *
	 */
	public static function setIniVariables(){

		if(defined('EMAIL_CUSTOM_SMTP_SERVER')){
			ini_set("SMTP", EMAIL_CUSTOM_SMTP_SERVER); //"smtp.example.com"
		}
		if(defined('EMAIL_CUSTOM_SMTP_FROM')){
			ini_set("sendmail_from", EMAIL_CUSTOM_SMTP_FROM); //"user@example.com"
		}

	}

	/*
	 * An error log function for this class
	 *
	 * @param	string $msg		The message to send to the error log
	 *
	 */
	public static function l($msg){
		if(self::$enableErrorLogs){
			error_log($msg);
		}
	}

}
Posted in , and tagged , .

Leave a Reply

Your email address will not be published. Required fields are marked *