Zoklet.net

Go Back   Zoklet.net > Technology > Technophiles and Technophiliacs > Codes of all kinds

Reply
 
Thread Tools
  #1  
Old 04-15-2009, 05:23 AM
Axiom Axiom is offline
Duke
 
Join Date: May 2008
Thanks: 21
Thanked 53 Times in 42 Posts
Default PHP Class - HTML Email & Attachments

A PHP class for the mail() function with support for HTML emails and easy file attachment syntax...


Example to send a Plain Text / HTML Email
Code:
<?php
require_once('email.class.php');

# Message Variables
$email_address = 'zoklet@example.com';
$subject = 'Subject Line Here';
$body = '<h2>Hello World!</h2><p>This is something with <b>HTML</b> <u>formatting</u>.</p>';

# Send email
$email = new email_message;
$email->send($email_address,$subject,$body);

?>

Example with 2 Attachments
Code:
<?php
require_once('email.class.php');

# Message Variables
$email_address = 'zoklet@example.com';
$subject = 'Subject Line Here';
$body = '<h2>Hello World!</h2><p>This is something with <b>HTML</b> <u>formatting</u>.</p>';

# Send email
$email = new email_message;
$email->attach_file('path_to_text_file1.txt');
$email->attach_file('path_to_image1.png');
$email->send($email_address,$subject,$body);

?>
Required Class File - email.class.php
Code:
<?php
/*
  email.class.php 

  Wed 15 Apr 2009

	*
	* WARNING! For development reasons the Send Function will always return true on a localhost server.
	* - Be sure to change default reply values to correct domain in __construct Function -
	*

*/

if (strpos ($_SERVER['PHP_SELF'], 'email.class.php') !== false) {
    die ('This file can not be used on its own.');
}

class email_message {

	private $to_email_address;
	private $cc_email_address;
	private $email_subject;
	private $email_message;
	private $reply_from_name;
	private $reply_email_address;
	private $email_headers;
	private $eol;
	private $mime_boundaryAlternative;
	private $mime_boundaryMixed;
	private $file_attachments;
	private $status;
	private $error;

	function __construct($reply_email_address='default@example.com',$from_name='Zoklet Email Class') {

	  #Assign Reply Values
	  $this->reply_from_name = $from_name;
	  $this->reply_email_address = $reply_email_address;

	  #Generate End Line & Section Boudary Markers
	  $this->eol="\r\n";
	  $this->mime_boundaryAlternative = 'PHP-alt-' . md5(date('r', time()));
	  $this->mime_boundaryMixed = 'PHP-mixed-' . md5(date('r', time())); 
	  $this->file_attachments = null;

	}

	function attach_file ($path, $mime_type=null) {

	  if (is_null($this->file_attachments)) {
	  $this->file_attachments = array();
	  }

	  # If mime_type not forced try to retrieve from file
	  $mime_type = (is_null($mime_type)) ? $this->getContentType($path) : $mime_type ;
	  array_push($this->file_attachments, Array("path"=>$path, "file_name"=>basename($path), "content_type"=>$mime_type));

	}

	function send($to_email_address,$subject,$body,$cc_email_address=null) {

	  $this->error = null;

	  $this->to_email_address = $to_email_address;
	  $this->email_subject = $subject;
	  $this->cc_email_address = $cc_email_address;

	  if ($this->to_email_address == '') {
	  $this->error = $this->error . '<li>Invalid Email Adress Supplied: Can not send email.</li>';
	  }
	  if ($this->email_subject == '') {
	  $this->error = $this->error . '<li>Invalid Email Subject Supplied: Can not send email.</li>';
	  }
	  if ($body == '') {
	  $this->error = $this->error . '<li>Invalid Email Message Supplied: Can not send email.</li>';
	  }


	  # Generate Email Headers
	  if (is_null($this->reply_email_address) || trim($this->reply_email_address) == '') {

	  $this->error = $this->error . '<li>Invalid Reply Email Adress Supplied: Can not send email.</li>';

	  } else {

	    # If a Reply Name has not been supplied then use Reply Email Address as name.
	    $this->reply_from_name = (isset($this->reply_from_name) && trim($this->reply_from_name) != '') ? $this->reply_from_name : $this->reply_email_address;

	    # Common Headers
	    $this->email_headers .= "From: ".$this->reply_from_name."<".$this->reply_email_address.">".$this->eol;
	    $this->email_headers .= "Reply-To: ".$this->reply_from_name."<".$this->reply_email_address.">".$this->eol;

	    if (!is_null($this->cc_email_address) && $this->cc_email_address != '') {
	    $this->email_headers .= "Cc: " . $this->cc_email_address . $this->eol;
	    }

	    $this->email_headers .= "Return-Path: ".$this->reply_from_name."<".$this->reply_email_address.">".$this->eol;    
	    $this->email_headers .= "Message-ID: <".time()."-".$this->reply_email_address.">".$this->eol;
	    $this->email_headers .= "X-Mailer: PHP v".phpversion().$this->eol;          // Help avoid spam-filters

	    if (isset($this->file_attachments)) {

	    # Boundry for Plain Text, HTML & Attchments
	    $this->email_headers .= 'MIME-Version: 1.0'. $this->eol . $this->eol;
	    $this->email_headers .= 'Content-Type: multipart/mixed; boundary="' . $this->mime_boundaryMixed . '"' . $this->eol . $this->eol;

	    # Add the Alternative Boundary to Body of Message  (NOTE THIS IS GOING INTO email_message and not email_headers)
	    $this->email_message .= "--" . $this->mime_boundaryMixed . $this->eol;
	    $this->email_message .= 'Content-Type: multipart/alternative; boundary="' . $this->mime_boundaryAlternative . '"' . $this->eol . $this->eol;

	    } else {

	    # Boundry for Plain Text & HTML ONLY
	    $this->email_headers .= 'MIME-Version: 1.0'. $this->eol . $this->eol;
	    $this->email_headers .= 'Content-Type: multipart/alternative; boundary="' . $this->mime_boundaryAlternative . '"' . $this->eol . $this->eol;

	    }

	  }

	  # Text Version
	  $this->email_message .= "--" . $this->mime_boundaryAlternative . $this->eol;
	  $this->email_message .= "Content-Type: text/plain; charset=iso-8859-1".$this->eol;
	  $this->email_message .= "Content-Transfer-Encoding: 8bit".$this->eol.$this->eol;
	  $this->email_message .= strip_tags(str_replace(array("<!-- new-line -->","<br>","</p>","<br />","<BR>","<BR />","</P>","</h2>","</h1>","</H2>","</H1>"), "\n", str_replace(array("&nbsp;","\n", "\r", "\t", "\o", "\xOB"), '', $body))) . $this->eol . $this->eol;

	  # HTML Version
	  $this->email_message .= "--" . $this->mime_boundaryAlternative . $this->eol;
	  $this->email_message .= "Content-Type: text/html; charset=iso-8859-1".$this->eol;
	  $this->email_message .= "Content-Transfer-Encoding: 8bit".$this->eol.$this->eol;
	  $this->email_message .= $body . $this->eol . $this->eol;

	  # Finished Plain Text / HTML Section
	  $this->email_message .= "--" . $this->mime_boundaryAlternative . "--" . $this->eol . $this->eol;

	  if (isset($this->file_attachments))
	  {

	    for($i=0; $i < count($this->file_attachments); $i++)
	    {

	      if (is_file($this->file_attachments[$i]["path"])) {       

	      $handle=fopen($this->file_attachments[$i]["path"], 'rb');
	      $f_contents=fread($handle, filesize($this->file_attachments[$i]["path"]));
	      $f_contents=chunk_split(base64_encode($f_contents));    // Encode The Data For Transition using base64_encode();
	      fclose($handle);
 
	      # Attachment
	      $this->email_message .= "--" . $this->mime_boundaryMixed . $this->eol;
	      $this->email_message .= "Content-Type: " . $this->file_attachments[$i]["content_type"] . "; name=\"" . $this->file_attachments[$i]["file_name"] . "\"" . $this->eol;
	      $this->email_message .= "Content-Transfer-Encoding: base64" . $this->eol;
	      $this->email_message .= "Content-Description: " . $this->file_attachments[$i]["file_name"] . $this->eol;
	      $this->email_message .= "Content-Disposition: attachment; filename=\"" . $this->file_attachments[$i]["file_name"] . "\"" . $this->eol . $this->eol; // !IMPORTANT: Needs 2 EOLs
	      $this->email_message .= $f_contents . $this->eol . $this->eol;

	      } else {
	        $this->error = $this->error . '<li>Invalid File Attachment (' . $this->file_attachments[$i]["path"] . '): Can not send email.</li>';
	      }


	    }

	    # Finished Mixed / Attachments Section
	    $this->email_message .= "--" . $this->mime_boundaryMixed . "--" . $this->eol . $this->eol;

	  }  

	  if (is_null($this->error)){
 
	    	if ($_SERVER['HTTP_HOST'] == 'localhost') {

		####
	    	# Don't attempt to send on development server. Return True
		# print $this->email_message;
		#

	        $this->error = $this->error . '<li>Localhost Detected - Email was not sent.</li>';
	    	$this->status = 1;

	    	} else {

	    	# SEND THE EMAIL
	    	ini_set(sendmail_from,$this->reply_email_address);  // Windows Environment work around
 	    	$this->status = @mail( $this->to_email_address, $this->email_subject, $this->email_message, $this->email_headers );

	    	ini_restore(sendmail_from);

	    	}

	  } else {

	    # Errors Present - Do not attempt to send.
	    $this->status = 0;

	  }

	  return $this->status;

	}

	private function getContentType($filename) { 

        $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            # images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            # archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            # audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            # adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            # ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            # open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet'

       	);

        $ext = strtolower(array_pop(explode('.',$filename)));
        if (array_key_exists($ext, $mime_types)) {

        	return $mime_types[$ext];

	} elseif (function_exists('finfo_open')) {

        	$finfo = finfo_open(FILEINFO_MIME);
		$mimetype = finfo_file($finfo, $filename);
		finfo_close($finfo);
		return $mimetype;

	} elseif (function_exists('mime_content_type')) {

		$mimetype = mime_content_type($filename);
		return $mimetype;

	} else { return 'application/octet-stream'; }


	}

	function output_values() { 

	# Debug Only
	$data = 'To Email: ' . $this->to_email_address . '<br>';
	$data = $data . 'Subject: ' . $this->email_subject . '<br>';
	$data = $data . 'Message: ' . $this->email_message . '<br>';
	$data = $data . 'Reply Name: ' . $this->reply_from_name . '<br>';
	$data = $data . 'Reply Email: ' . $this->reply_email_address . '<br>';
	$data = $data . 'Headers: "' . $this->email_headers . '"<br>';
	$data = $data . 'Status: ' . $this->status . '<br><br>';
	$data = $data . 'Errors: <ul>' . $this->error . '</ul>';

	return $data;

	}


};

?>
Examples of Settings and Extras
eg. Cc Addresses, Forcing mime types on attachments and Setting the senders Email & Name.

Code:
<?php
require_once('email.class.php');

# Message Variables
$email_address = 'zoklet@example.com';
$subject = 'Subject Line Here';
$body = '<h2>Hello World!</h2><p>This is something with <b>HTML</b> <u>formatting</u>.</p>';

# Example of setting the Senders Reply Address and Senders Name
$email = new email_message('senders_reply_adress@example.com','Senders Name');

# Example of how to force a Content Mime Type to the attachment
$email->attach_file('path_to_file.txt','text/plain');

# Example of how to Cc another email address
$email->send($email_address,$subject,$body,'cc_email_address_here@example.com');

?>

Last edited by Axiom; 05-18-2009 at 11:57 PM.
Reply With Quote
  #2  
Old 04-15-2009, 05:29 AM
Craigslist.org Craigslist.org is offline
Seņor Member
 
Join Date: Jan 2009
Location: up your butt
Thanks: 461
Thanked 171 Times in 106 Posts
Send a message via ICQ to Craigslist.org Send a message via AIM to Craigslist.org Send a message via MSN to Craigslist.org Send a message via Yahoo to Craigslist.org
Default Re: PHP Class - HTML Email & Attachments

What exactly does it do? Ive got something similar I think..... Its a recommend form that sends emails.
Reply With Quote
  #3  
Old 04-15-2009, 05:39 AM
Axiom Axiom is offline
Duke
 
Join Date: May 2008
Thanks: 21
Thanked 53 Times in 42 Posts
Default Re: PHP Class - HTML Email & Attachments

It's a reusable email class I made today for easily sending HTML emails and File Attachments through the default mail() function of PHP. Basically it formats the email headers for you automatically to send Plain Text, HTML and File Attachment content portions within a single email.

Email clients with HTML support will see the HTML portion of the email, Plain Text Only email clients will still receive the email but with the HTML tags stripped out and spaced. Attachments are sent as close as I could get to the Mixed Content Type standard for formatting email headers. You can use it as per example code blocks 1, 2 & 4...

Opps: That's mail() function not sendmail() function...

Last edited by Axiom; 04-15-2009 at 05:44 AM.
Reply With Quote
  #4  
Old 04-15-2009, 05:44 AM
Craigslist.org Craigslist.org is offline
Seņor Member
 
Join Date: Jan 2009
Location: up your butt
Thanks: 461
Thanked 171 Times in 106 Posts
Send a message via ICQ to Craigslist.org Send a message via AIM to Craigslist.org Send a message via MSN to Craigslist.org Send a message via Yahoo to Craigslist.org
Default Re: PHP Class - HTML Email & Attachments

Quote:
Originally Posted by Axiom View Post
It's a reusable email class I made today for easily sending HTML emails and File Attachments through the default sendmail() function of PHP. Basically it formats the email headers for you automatically to send Plain Text, HTML and File Attachment content portions within a single email.

Email Clients with HTML support will see the HTML portion of the email, Plain Text Only email clients will still receive the email but with the HTML tags stripped out and spaced. Attachments are sent as close as I could get to the Mixed Content Type standard for formatting email headers. You can use it as per example code blocks 1,2 & 4...
cool sounds interesting. Can you also make smileys work for popular emails?
Like if I send an email thru this thing to hotmail could you get the smiley from msn to show up as an image and same with yahoo? Or would they just show up as text?
Reply With Quote
  #5  
Old 04-15-2009, 05:50 AM
Axiom Axiom is offline
Duke
 
Join Date: May 2008
Thanks: 21
Thanked 53 Times in 42 Posts
Default Re: PHP Class - HTML Email & Attachments

Quote:
Originally Posted by Craigslist.org View Post
cool sounds interesting. Can you also make smileys work for popular emails?
Like if I send an email thru this thing to hotmail could you get the smiley from msn to show up as an image and same with yahoo? Or would they just show up as text?
Hmm, not exactly as all email content (including any attachments) are sent as plain text. That's just how they do it - but you could send it as a HTML email and include the image of the smiley in the text.

eg. <p>Hello World<img src="http://www.example.com/smiley.gif" /></p> - That will work...

If you really wanted you could write a function to parse the body of your message for smiley's and replace them with images automatically and then send it as HTML normally through the class. You can do what you want with it, that's why I made it a class...
Reply With Quote
The following users say "It is so good to hear it!":
Craigslist.org (04-15-2009)
  #6  
Old 04-15-2009, 05:57 AM
Craigslist.org Craigslist.org is offline
Seņor Member
 
Join Date: Jan 2009
Location: up your butt
Thanks: 461
Thanked 171 Times in 106 Posts
Send a message via ICQ to Craigslist.org Send a message via AIM to Craigslist.org Send a message via MSN to Craigslist.org Send a message via Yahoo to Craigslist.org
Default Re: PHP Class - HTML Email & Attachments

Quote:
Originally Posted by Axiom View Post
Hmm, not exactly as all email content (including any attachments) are sent as plain text. That's just how they do it - but you could send it as a HTML email and include the image of the smiley in the text.

eg. <p>Hello World<img src="http://www.example.com/smiley.gif" /></p> - That will work...

If you really wanted you could write a function to parse the body of your message for smiley's and replace them with images automatically and then send it as HTML normally through the class. You can do what you want with it, that's why I made it a class...
cool I should try this out.

Do you know how I can fix this? http://www.zoklet.net/bbs/showthread.php?t=23761
Reply With Quote
  #7  
Old 05-25-2009, 10:20 PM
Axiom Axiom is offline
Duke
 
Join Date: May 2008
Thanks: 21
Thanked 53 Times in 42 Posts
Default Re: PHP Class - HTML Email & Attachments

I just got an error using this class when sending a Mixed/Alternative text/html email on an Apache Cluster set up. The error meant the entire message was displayed to the user as plaint-text including the html portion.

This can be fix by removing the second End Of Line indicator from a header as below...

On the line after this...
Code:
# Boundry for Plain Text & HTML ONLY
Replace this...
Code:
$this->email_headers .= 'MIME-Version: 1.0'. $this->eol . $this->eol;
With this...
Code:
$this->email_headers .= 'MIME-Version: 1.0'. $this->eol;// . $this->eol;
I did not test attachments on this set up. If multipart messages with attachments give you the same error - Try removing the second $this->eol from the MIME-Version header under the line "# Boundry for Plain Text, HTML & Attchments" also.
Reply With Quote
Reply

Bookmarks

Tags
attachments, class, email, html, php

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
People who take a writing class should be required to take a word processing class Nightshade Pissin' Each Other Off 15 04-24-2009 09:02 PM
Could someone help me validate webpages for my html class? PooPfish Codes of all kinds 1 04-13-2009 11:16 PM
Anyone Know HTML? Craigslist.org Bat Country 4 04-07-2009 03:32 AM
Silly HTML Questions - Image in the div class title Spam Man Sam Codes of all kinds 6 02-07-2009 06:58 PM
sending HTML form to email using PHP (please help) GermanyOrFlorida Codes of all kinds 1 01-16-2009 08:44 PM


All times are GMT. The time now is 10:58 PM.


Hot Topics
On IRC
Users: 4
Messages/minute: 0
Topic: "http://www.zoklet.net/..."
Users: 22
Messages/minute: 0
Topic: "buttpee"
Users: 10
Messages/minute: 0
Topic: "11:37 < mib_i8mfin> so wie ich die website hier sehe las..."
Advertisements
Your ad could go right HERE! Contact us!

Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.