Email Code
  Home arrow Email Code arrow PHP Text / HTML Email with Unlimited A...
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
EMAIL CODE

PHP Text / HTML Email with Unlimited Attachments
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 19
    2004-01-16

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    This class sends email and allows for multiple attachments and text or HTML emails. Support for multipart/alternative messages just added, allowing for a text and html version of the same email to be sent at the same time, letting the recipiant's email client decide which is best to display. Simple to use and handles all errors and header complications from the user. Attach files using $email->Attach("filepath", "mimetype"); To send HTML emails set $email->TextOnly to false and set $email->Content to the appropriate HTML to send. See index.php file in the included zip folder for example usage.

    NOTE**** if using Qmail as the outgoing mail server change the line define("EmailNewLine", "\r\n"); to be define("EmailNewLine", "\n"); This has to do with Qmail replacing all '\n' with '\r\n' without realizing there is already a leading \r.

    By : wmfwlr

    <?
    //--- START OF TESTING FILE ---
    //** load email class definition.

    include('class.Email.php');

    //** establish to,from, and any other recipiants.

    $Sender = "you@there.com";
    $Recipiant = "me@here.com";
    $Cc = "them@there.com";
    $Bcc = "";

    //** create the text and HTML versions of the body content here.

    $textVersion = "Hello World!";
    $htmlVersion = "<font face='verdana' color='blue'><b>Hello World</b></font>";

    unset($msg);

    //** !!!! SEND A PLAIN TEXT EMAIL !!!!
    //** create the new message using the to, from, and email subject.

    $msg = new Email($Recipiant, $Sender, "A Test Plain Text Email!");
    $msg->Cc = $Cc;
    $msg->Bcc = $Bcc;

    //** set the message to be text only and set the email content.

    $msg->TextOnly = true;
    $msg->Content = $textVersion;

    //** send the email message.

    $SendSuccess = $msg->Send();

    echo "Plain text email was ",
    ($SendSuccess ? "sent" : "not sent"), "<br>";

    unset($msg);

    //** !!!! SEND AN HTML EMAIL w/ATTACHMENT !!!!
    //** create the new message using the to, from, and email subject.

    $msg = new Email($Recipiant, $Sender, "A Test HTML Email!");
    $msg->Cc = $Cc;
    $msg->Bcc = $Bcc;

    //** set the message to be text only and set the email content.

    $msg->TextOnly = false;
    $msg->Content = $htmlVersion;

    //** attach this scipt itself to the message.

    $msg->Attach(__FILE__, "text/plain");

    //** send the email message.

    $SendSuccess = $msg->Send();

    echo "HTML email w/attachment was ",
    ($SendSuccess ? "sent" : "not sent"), "<br>";

    unset($msg);

    //** !!!! SEND A MULTIPART/ALTERNATIVE EMAIL !!!!
    //** create the new message using the to, from, and email subject.

    $msg = new Email($Recipiant, $Sender, "A Test Multipart Alternative Email!");
    $msg->Cc = $Cc;
    $msg->Bcc = $Bcc;

    //** set the message to be a multiprat/alternative email. This allows for
    //** multiple versions of same content.
    //** NOTE: you cannot send attachments when a message is set to be
    //** multipart/alternative. there is also no way to switch
    //** back to normal multipart/mixed after this call.

    $msg->SetMultipartAlternative($textVersion, $htmlVersion);

    //** send the email message.

    $SendSuccess = $msg->Send();

    echo "Multipart/alternative email was ",
    ($SendSuccess ? "sent" : "not sent"), "<br>";

    //--- END OF TESTING FILE ---
    ?>


    <?
    //--- START OF CLASS DEFINITION ---
    //** ©William Fowler (wmfwlr@cogeco.ca)
    //** MAY 13/2004, Version 1.1
    //** - added support for CC and BCC fields.
    //** - added support for multipart/alternative messages.
    //** - added ability to create attachments manually using literal content.
    //** DECEMBER 15/2003, Version 1.0

    if(isset($GLOBALS["emailmsgclass_php"])) { return; } //** onlyinclude once.
    $GLOBALS["emailmsgclass_php"] = 1; //** filewas included.

    //** the newline character(s) to be used when generating an email message.

    define("EmailNewLine", "\r\n");

    //** the unique X-Mailer identifier for emails sent with this tool.

    define("EmailXMailer", "PHP-EMAIL,v1.1 (William Fowler)");

    //** the default charset values for both text and HTML emails.

    define("DefaultCharset", "iso-8859-1");

    //**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    //**EMAIL_MESSAGE_CLASS_DEFINITION********************************************
    //** The Email class wrappers PHP's mail function into a class capable of
    //** sending attachments and HTML email messages. Custom headers can also be
    //** included as if using the mail function.

    class Email
    {
    //** (String) the recipiant email address, or comma separated addresses.

    var $To = null;

    //** (String) the recipiant addresses to receive a copy. Can be a comma
    //** separated addresses.

    var $Cc = null;

    //** (String) the recipiant addresses to receive a hidden copy. Can be a
    //** comma separated addresses.

    var $Bcc = null;

    //** (String) the email address of the message sender.

    var $From = null;

    //** (String) the subject of the email message.

    var $Subject = null;

    //** (String) body content for the message. Must be plain text or HTML based
    //** on the 'TextOnly' field. This field is ignored if
    //** SetMultipartAlternative() is called with valid content.

    var $Content = null;

    //** an array of EmailAttachment instances to be sent with this message.

    var $Attachments;

    //** any custom header information that must be used when sending email.

    var $Headers = null;

    //** whether email to be sent is a text email or a HTML email.

    var $TextOnly = true;

    //** the charset of the email to be sent (initially none, let type decide).

    var $Charset = null;

    //** Create a new email message with the parameters provided.

    function Email($to=null, $from=null, $subject=null, $headers=null)
    {
    $this->To = $to;
    $this->From = $from;
    $this->Subject = $subject;
    $this->Headers = $headers;

    //** create an empty array for attachments. NULL out attachments used for
    //** multipart/alternative messages initially.

    $this->Attachments = Array();
    $this->Attachments["text"] = null;
    $this->Attachments["html"] = null;
    }
    //** Returns: Boolean
    //** Set this email message to contain both text and HTML content.
    //** If successful all attachments and content are ignored.

    function SetMultipartAlternative($text=null, $html=null)
    {
    //** non-empty content for the text and HTML version is required.

    if(strlen(trim(strval($html))) == 0 || strlen(trim(strval($text))) == 0)
    return false;
    else
    {
    //** create the text email attachment based on the text given and the standard
    //** plain text MIME type.

    $this->Attachments["text"] = new EmailAttachment(null, "text/plain");
    $this->Attachments["text"]->LiteralContent = strval($text);

    //** create the html email attachment based on the HTML given and the standard
    //** html text MIME type.

    $this->Attachments["html"] = new EmailAttachment(null, "text/html");
    $this->Attachments["html"]->LiteralContent = strval($html);

    return true; //** operation was successful.
    }
    }
    //** Returns: Boolean
    //** Create a new file attachment for the file (and optionally MIME type)
    //** given. If the file cannot be located no attachment is created and
    //** FALSE is returned.

    function Attach($pathtofile, $mimetype=null)
    {
    //** create the appropriate email attachment. If the attachment does not
    //** exist the attachment is not created and FALSE is returned.

    $attachment = new EmailAttachment($pathtofile, $mimetype);
    if(!$attachment->Exists())
    return false;
    else
    {
    $this->Attachments[] = $attachment; //** add the attachment to list.
    return true; //** attachment successfully added.
    }
    }
    //** Returns: Boolean
    //** Determine whether or not the email message is ready to be sent. A TO and
    //** FROM address are required.

    function IsComplete()
    {
    return (strlen(trim($this->To)) > 0 && strlen(trim($this->From)) > 0);
    }
    //** Returns: Boolean
    //** Attempt to send the email message. Attach all files that are currently
    //** valid. Send the appropriate text/html message. If not complete FALSE is
    //** returned and no message is sent.

    function Send()
    {
    if(!$this->IsComplete()) //** message is not ready to send.
    return false; //** no message will be sent.

    //** generate a unique boundry identifier to separate attachments.

    $theboundary = "-----" . md5(uniqid("EMAIL"));

    //** the from email address and the current date of sending.

    $headers = "Date: " . date("r", time()) . EmailNewLine .
    "From: $this->From" . EmailNewLine;

    //** if a non-empty CC field is provided add it to the headers here.

    if(strlen(trim(strval($this->Cc))) > 0)
    $headers .= "CC: $this->Cc" . EmailNewLine;

    //** if a non-empty BCC field is provided add it to the headers here.

    if(strlen(trim(strval($this->Bcc))) > 0)
    $headers .= "BCC: $this->Bcc" . EmailNewLine;

    //** add the custom headers here, before important headers so that none are
    //** overwritten by custom values.

    if($this->Headers != null && strlen(trim($this->Headers)) > 0)
    $headers .= $this->Headers . EmailNewLine;

    //** determine whether or not this email is mixed HTML and text or both.

    $isMultipartAlternative = ($this->Attachments["text"] != null &&
    $this->Attachments["html"] != null);

    //** determine the correct MIME type for this message.

    $baseContentType = "multipart/" . ($isMultipartAlternative ?
    "alternative" : "mixed");

    //** add the custom headers, the MIME encoding version and MIME typr for the
    //** email message, the boundry for attachments, the error message if MIME is
    //** not suppported.

    $headers .= "X-Mailer: " . EmailXMailer . EmailNewLine .
    "MIME-Version: 1.0" . EmailNewLine .
    "Content-Type: $baseContentType; " .
    "boundary=\"$theboundary\"" . EmailNewLine . EmailNewLine;

    //** if a multipart message add the text and html versions of the content.

    if($isMultipartAlternative)
    {
    //** add the text and html versions of the email content.

    $thebody = "--$theboundary" . EmailNewLine .
    $this->Attachments["text"]->ToHeader() . EmailNewLine .
    "--$theboundary" . EmailNewLine .
    $this->Attachments["html"]->ToHeader() . EmailNewLine;
    }
    //** if either only html or text email add the content to the email body.

    else
    {
    //** determine the proper encoding type and charset for the message body.

    $theemailtype = "text/" . ($this->TextOnly ? "plain" : "html");
    if($this->Charset == null)
    $this->Charset = DefaultCharset;

    //** add the encoding header information for the body to the content.

    $thebody = "--$theboundary" . EmailNewLine .
    "Content-Type: $theemailtype; charset=$this->Charset" .
    EmailNewLine . "Content-Transfer-Encoding: 8bit" .
    EmailNewLine . EmailNewLine . $this->Content .
    EmailNewLine . EmailNewLine;

    //** loop over the attachments for this email message and attach the files
    //** to the email message body. Only if not multipart alternative.

    foreach($this->Attachments as $attachment)
    {
    //** check for NULL attachments used by multipart alternative emails. Do not
    //** attach these.

    if($attachment != null)
    {
    $thebody .= "--$theboundary" . EmailNewLine .
    $attachment->ToHeader() . EmailNewLine;
    }
    }
    }
    //** end boundry marker is required.

    $thebody .= "--$theboundary--";

    //** attempt to send the email message. Return the operation success.

    return mail($this->To, $this->Subject, $thebody, $headers);
    }
    }
    //******************************************END_EMAIL_MESSAGE_CLASS_DEFINITION
    //**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    //**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    //**EMAIL_ATTACHMENT_CLASS_DEFINITION*****************************************
    //** The EmailAttachment class links a file in the file system to the
    //** appropriate header to be included in an email message. if the file does
    //** not exist the attachment will not be sent in any email messages. It can
    //** also be used to generate an attachment from literal content provided.

    class EmailAttachment
    {
    //** (String) the full path to the file to be attached.

    var $FilePath = null;

    //** (String) the MIME type for the file data of this attachment.

    var $ContentType = null;

    //** binary content to be used instead the contents of a file.

    var $LiteralContent = null;

    //** Creates a new email attachment ffrom the file path given. If no content
    //** type is given the default 'application/octet-stream' is used.

    function EmailAttachment($pathtofile=null, $mimetype=null)
    {
    //** if no MIME type is provided use the default value specifying binary data.
    //** Otherwise use the MIME type provided.

    if($mimetype == null || strlen(trim($mimetype)) == 0)
    $this->ContentType = "application/octet-stream";
    else
    $this->ContentType = $mimetype;

    $this->FilePath = $pathtofile; //** save the path to the file attachment.
    }
    //** Returns: Boolean
    //** Determine whether literal content is provided and should be used as the
    //** attachment rather than a file.

    function HasLiteralContent()
    {
    return (strlen(strval($this->LiteralContent)) > 0);
    }
    //** Returns: String
    //** Get the binary string data to be used as this attachment. If literal
    //** content is provided is is used, otherwise the contents of the file path
    //** for this attachment is used. If no content is available NULL is returned.

    function GetContent()
    {
    //** non-empty literal content is available. Use that as the attachment.
    //** Assume the user has used correct MIME type.

    if($this->HasLiteralContent())
    return $this->LiteralContent;

    //** no literal content available. Try to get file data.

    else
    {
    if(!$this->Exists()) //** file does not exist.
    return null; //** no content is available.
    else
    {
    //** open the file attachment in binary mode and read the contents.

    $thefile = fopen($this->FilePath, "rb");
    $data = fread($thefile, filesize($this->FilePath));
    fclose($thefile);
    return $data;
    }
    }
    }
    //** Returns: Boolean
    //** Determine whether or not the email attachment has a valid, existing file
    //** associated with it.

    function Exists()
    {
    if($this->FilePath == null || strlen(trim($this->FilePath)) == 0)
    return false;
    else
    return file_exists($this->FilePath);
    }
    //** Returns: String
    //** Generate the appropriate header string for this email attachment. If the
    //** the attachment content does not exist NULL is returned.

    function ToHeader()
    {
    $attachmentData = $this->GetContent(); //** get content for the header.
    if($attachmentData == null) //** no valid attachment content.
    return null; //** no header can be generted.

    //** add the content type and file name of the attachment.

    $header = "Content-Type: $this->ContentType;";

    //** if an attachment then add the appropriate disposition and file name(s).

    if(!$this->HasLiteralContent())
    {
    $header .= " name=\"" . basename($this->FilePath) . "\"" . EmailNewLine .
    "Content-Disposition: attachment; filename=\"" .
    basename($this->FilePath) . "\"";
    }
    $header .= EmailNewLine;

    //** add the key for the content encoding of the attachment body to follow.

    $header .= "Content-Transfer-Encoding: base64" . EmailNewLine .
    EmailNewLine;

    //** add the attachment data to the header. encode the binary data in BASE64
    //** and break the encoded data into the appropriate chunks.

    $header .= chunk_split(base64_encode($attachmentData), 76, EmailNewLine) .
    EmailNewLine;

    return $header; //** return the headers generated by file.
    }
    }
    //***************************************END_EMAIL_ATTACHMENT_CLASS_DEFINITION
    //**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    //--- END OF CLASS DEFINITION ---
    ?>

    Click to Download File



    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Email Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Download the free Web Application Security eKit

    Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z

    IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects.
    FREE! Go There Now!


    NEW! IBM Rational ClearCase Innovator's Series

    Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase.
    FREE! Go There Now!


    NEW! IBM Rational Systems Development e-Kit

    As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br />
    FREE! Go There Now!


    NEW! Integrating XML into Your Enterprise Using Data Federation

    XML has become a common way of storing business data as flat files and many data server vendors including IBM have provided ways to store this data within relational database systems. Increasingly collections of XML files are accessed like databases using an xQuery and other XML standard mechanisms. Businesses find the need to combine the traditional tabular structured data with XML formatted data. In this webcast, you’ll learn about IBM’s WebSphere Federation Server technology, which provides users with the ability to integrate these two data formats.
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    NEW! The role of integrated requirements management in software delivery

    This paper is about the critical role that a discipline called integrated require­ments management can play in helping to ensure that your business goals and IT investments are continuously aligned—whether you are sourcing, integrat­ing, building or maintaining software. It also looks at ways that automated IBM Rational® products can work together to help you use requirements in the very best way.
    FREE! Go There Now!


    NEW! Trial download: IBM Informix Dynamic Server Express Edition V11.0

    Informix Dynamic Server (IDS) Express Edition offers outstanding online transaction processing (OLTP) database performance, while helping to simplify and automate many of the tasks associated with deploying databases for small business applications. IDS 11 further extends the ease of management and applications integration with the Admin API and Scheduler, high availability with Continuous Log Restore for backup server recovery in case of a primary server failure, and column level encryption to protect personal and company private data.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Method Composer V7.2

    Get a free trial download of the latest version of IBM Rational Method Composer V7.2 which helps you deliver customized yet consistent process guidance to your project teams and IT organization, and includes the latest version of IBM Rational Unified Process (RUP), which has provided process guidance to teams since 1996.
    FREE! Go There Now!


    NEW! Using Rational Business Developer to enhance your developer productivity

    Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    EMAIL CODE ARTICLES

    - Basic Ajax contact form
    - Random validation image
    - tinySendMail
    - SaferMail 0.7
    - Smtp Auth Email Script
    - Search Mime Email Structure
    - PHP Text / HTML Email with Attachments 2.1
    - Simple way to send mail wih one attached Doc...
    - Generic POP3 Class
    - PHP Text / HTML Email with Unlimited Attachm...
    - Another SendMail
    - email with attachment
    - Get Email Addresses from Strings
    - EmailCode
    - Email Validation - Gone Wild





    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 12 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek