Email Code
  Home arrow Email Code arrow MultiTypeMail
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  
Forums Sitemap 
Download TestComplete 
JMSL Numerical Library 
IBM® developerWorks
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

MultiTypeMail
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2002-12-27

    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


    Sends MIME emails from your site. Allows for Raw text and HTML versions of same message and attachment at the same time. Performs simple validation on email addresses as well as ensuring HTML does not contain any "nasties". Listing includes simple HTML interface to drive code. Tested on Unix/ PHP4 only.

    By : mgscox

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>

    <?php

    function multitypemail($message,$ishtml,$subject,$toname,$toemail,$fromname,$fromemail,$attachmentloc,$attfilename,$cc,$ccname,$bcc,$bccname) {
    //$message - text or html message to be sent
    //$ishtml - flag set to true if $message is HTML, otherwise set to false
    //$subject - subject line of email
    //$toname - name of person receiving email (use only if sending to a single person)
    //$toemail - email address of recipient (separate multiple addresses by a comma, use ! as first character to send to each receipient separately
    //$fromname - name of person sending email
    //$fromemail - email address of sender
    //$attachmentloc - path and filename of attachment (on the server), or empty string for no attachment
    //$attfilename - filename and extension only
    //$cc - email address of person to courtesy copy (or empty string)
    //$cc - name of person to courtesy copy (or empty string)
    //$bcc - email address of person to blind courtesy copy (or empty string)
    //$bcc - address of person to blind courtesy copy (or empty string)
    $returnval=0; // returns integer, zero for success (okay, its a bit naff but at least it says something!)

    global $HTTP_HOST; // name of host used for a base-reference, e.g. www.myhost.com

    /* ************************** */
    /* Begin local procedures */
    /* ************************** */
    //strip out all non-safe HTML directives and any PHP & ASP directives
    function safeHTML($str)
    {
    $approvedtags = array(
    "p"=>2, // 2 means accept all qualifiers: <foo bar>
    "b"=>1, // 1 means accept the tag only: <foo>
    "i"=>1, // note, recommend not allowing <img> as these can be used to call cgi-perl routines
    "a"=>2,
    "em"=>1,
    "br"=>1,
    "strong"=>1,
    "blockquote"=>1,
    "tt"=>1,
    "hr"=>1,
    "li"=>1,
    "ol"=>1,
    "ul"=>1
    );

    $str = stripslashes($str);
    $str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>","<\\1>",$str);
    $str = eregi_replace("<a([^>]*)href=\"?([^\"]*)\"?([^>]*)>",
    "<a href=\"\\2\">", $str);
    $tmp = "";
    while (eregi("<([^> ]*)([^>]*)>",$str,$reg))
    {
    $i = strpos($str,$reg[0]);
    $l = strlen($reg[0]);
    if ($reg[1][0] == "/")
    $tag = strtolower(substr($reg[1],1));
    else
    $tag = strtolower($reg[1]);
    if ($a = $approvedtags[$tag])
    if ($reg[1][0] == "/")
    $tag = "</$tag>";
    elseif ($a == 1)
    $tag = "<$tag>";
    else
    $tag = "<$tag " . $reg[2] . ">";
    else
    $tag = "";
    $tmp .= substr($str,0,$i) . $tag;
    $str = substr($str,$i+$l);
    }
    $str = $tmp . $str;

    // Squash PHP tags unconditionally
    $str = ereg_replace("<\?php","",$str);
    $str = ereg_replace("<\?","",$str);

    // Squash ASP tags unconditionally
    $str = ereg_replace("<%","",$str);

    return $str;
    } // end safeHTML

    // check if email address is valid
    function validate_email($val)
    {
    if($val != "") {
    $pattern = "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/";
    if(preg_match($pattern, $val))
    return true;
    else
    return false;
    }
    else
    return false;
    }


    /* ************************** */
    /* End local procedures */
    /* ************************** */


    if ($ishtml) {
    $txtmessage="This is a multi-part HTML-based message. Please use an HTML compliant email client.";
    $message=safeHTML($message);
    }
    else {
    // if its raw text, create a simple HTML version of it for HTML compatible email clients
    $txtmessage=$message; // save rawtext version
    //next line translates text into HTML using the PHP built-in function 'htmlentities'
    $message="<HTML><HEAD><TITLE>MultiMail Message</TITLE></HEAD><BODY>".htmlentities($message,ENT_QUOTES)."</BODY></HTML>";
    $message=nl2br($message); //turn all hard coded newlines into HTML breaks
    }

    // If "to" list is prefixed with a pling then each recipient will be email'd separately so they cannot see other addresses
    if ($to[0]=="!") {
    $sendsep=1;
    $to=substr($to,1); }

    // build message headers
    // note use of \r\n (not just \n) in headers as this will work on all emailers
    $headers .= "From: $fromname <"."$fromemail".">\r\n";

    if(!$sendsep && $cc) { $headers .= "Cc: $ccname <$cc>\r\n"; }
    if(!$sendsep && $bcc) { $headers .= "Bcc: $bccname <$bcc>\r\n"; }

    // create a MIME boundary strings
    $mime_boundary = "=====MULTIMAIL." . md5(uniqid(time())) . "=====";
    $related_boundary = "=====MULTIMAIL." . md5(uniqid(time())) . "=====";
    $alternative_boundary = "=====MULTIMAIL." . md5(uniqid(time())) . "=====";

    // add MIME data to the message headers
    $headers .= "MIME-Version:1.0\r\n";
    $headers .= "Content-Type: multipart/mixed; \r\n\tboundary=\"$mime_boundary\";\r\n\r\n".
    "Content-Transfer-Encoding: 7bit\r\n".
    "This is a MIME-standard E-mail. If you are reading this, consider upgrading your e-mail client to a MIME-compatible client.";

    // start building a MIME message
    // first part is always the message body
    // encode an alternative section for raw text & HTML
    $email_message = "--" . $mime_boundary . "\r\n".
    "Content-Type: multipart/related;\r\n\tboundary=\"$related_boundary\"\r\n\r\n".
    "--".$related_boundary."\r\n".
    "Content-Type: multipart/alternative;\r\n\tboundary=\"$alternative_boundary\"\r\n\r\n".

    // add raw text alternative as 7-bit text
    $email_message .= "--" . $alternative_boundary . "\r\n".
    "Content-Type: text/plain;\r\n\tcharset=\"us-ascii\"\r\n".
    "Content-Transfer-Encoding: 7bit\r\n\r\n".
    "$txtmessage\r\n\r\n";

    // add HTML alternative part of message
    $email_message .= "--" . $alternative_boundary . "\r\n".
    "Content-Type:text/html;\r\n\tcharset=\"iso-8859-1\"\r\n" .
    "Content-Base: $HTTP_HOST\r\n" .
    "Content-Transfer-Encoding: 7bit\r\n\r\n" .
    $message . "\n\n";
    $email_message .= "--" . $alternative_boundary . "--\r\n";

    if ($attachmentloc!='' && filesize("$attachmentloc")>0) {
    $file = fopen("$attachmentloc",'rb');
    $data = fread($file,filesize("$attachmentloc"));
    fclose($file);
    $data = chunk_split(base64_encode($data)); // note same as transfer coding in line below

    // add the MIME data
    $email_message .= "--" . $related_boundary . "\r\n".
    "Content-Type: application/octet-stream;\r\n\tname=\"$attfilename\"\r\n".
    "Content-Transfer-Encoding: base64\r\n".
    "Content-Disposition: attachment; \r\n\tfilename=\"$attfilename\"\r\n\r\n".
    $data . "\r\n".
    "\r\n--$related_boundary--\r\n";
    }
    $email_message .= "--" . $mime_boundary . "--\r\n";

    if (!validate_email($from_email)) $returnval=1;
    $formattedto = "$toname <".$toemail.">";

    // send out the message
    if ($sendsep) {
    $allto = split(",", $to);
    for($x=0; $x<sizeof($allto); $x++) {
    if($allto[$x] == "") continue;
    if (!validate_email($allto[$x])) $returnval=2;
    $ok = mail($allto[$x], $subject, $email_message, $headers);
    }
    }
    else {
    if (!validate_email($toemail)) $returnval=2;
    $ok = mail($formattedto, $subject, $email_message, $headers);
    }

    if(!$ok)
    $returnval=3;

    return $returnval;
    }
    // end function multitypemail
    ?>

    <!-- Here is some very simple HTML just to drive the interface to the multi-mailer -->
    <head>
    <title>Multi-emailer</title>
    </head>
    <body>
    <?php
    if (!$sent) // note, assumes PHP setup so that all form variables passed as global variables (normal setup)
    print "<h1>Please enter the following info</h1><div class='font-family:verdana' align=center>".
    "<form method=post name=mailform action=$PHP_SELF ENCTYPE='multipart/form-data'>". // note ENCTYPE - without this browser won't upload file to server just pass its name
    "<table cellpadding=0 cellspacing=0 border=0><tbody>".
    "<tr><td>To addr</td><td><input name=to_addr></td></tr>".
    "<tr><td>To name</td><td><input name=to_name></td></tr>".
    "<tr><td>From addr</td><td><input name=from_addr></td></tr>".
    "<tr><td>From name</td><td><input name=from_name></td></tr>".
    "<tr><td>Subject</td><td><input name=subject></td></tr>".
    "<tr><td>Message is in HTML? (select for yes)</td><td><input type=checkbox name=htmlformat></td></tr>".
    "<tr><td>Message</td><td><textarea name=msg></textarea></td></tr>".
    "<tr><td>Attach file</td><td><input type=file name=attach></td></tr>".
    "<tr><td>Send you a courtesy copy?</td><td><input type=checkbox name=cc_me></td></tr>".
    "<tr><td>Send you a blind courtesy copy?</td><td><input type=checkbox name=bcc_me></td></tr>".
    "</tbody></table>".
    "<input type=hidden name=sent value=1>".
    "<input type=hidden name=localfilename>".
    "<input type=button value='Send email' onclick='document.mailform.localfilename.value=document.mailform.attach.value;document.mailform.submit();return true'>".
    "</form></div>";
    else {
    if ($cc_me=='on') {$cc=$from_addr; $cc_name=$from_name;}
    elseif ($bcc_me=='on') {$bcc=$from_addr; $bcc_name=$from_name;}
    if ($htmlformat=='on') $htmlon=1;
    else $htmlon=0;
    $i=strrpos($localfilename,"\\");
    if (!$i) $i=strrpos($localfilename,"/");
    $attfilename=substr($localfilename,($i+1));

    if (strrpos($attach,"\\\\")||strrpos($attach,"\/\/"))$attach=stripslashes($attach); // stip out extra slashes if web client added them
    $result=multitypemail($msg,$htmlon,$subject,$to_name,$to_addr,$from_name,$from_addr,$attach,$attfilename,$cc,$cc_name,$bcc,$bcc_name);

    if ($result==1) print "I'm sorry, but the address '$to_addr' is not valid.";
    elseif ($result==2) print "I'm sorry, but the address '$from_addr' is not valid.";
    elseif ($result==3) print "I'm sorry, but the email was not sent.";
    else print "Email sent successfully.<br>";
    print "<br><br>Please click <a href=$PHP_SELF?sent=0>here</a> to send another message.";
    }
    ?>
    </body>
    </html>

    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!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Download IBM WebSphere Portal V6.1 beta code

    Download the IBM WebSphere Portal V6.1 beta code and learn more about the rich features and enhancements in IBM WebSphere Portal V6.1. WebSphere Portal provides a composite application or business mashup framework and the advanced tooling needed to build flexible, SOA-based solutions, and scalability to meet the needs of any size organization.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z: Architecture

    Analysts, architects, and developers who have existing COBOL or PL/I skills and want to extend those skills to deploy new workloads on the mainframe can use the IBM Enterprise Modernization Sandbox for System z to find hands-on walkthroughs of common real world scenarios. The scenarios provide examples of how to rapidly design, create, assemble, test, and deploy high-quality Web, Web services, portal, and SOA applications for IBM CICS, IBM IMS, and IBM WebSphere Application Server.
    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! Maintaining QoS and Process Integrity in an SOA Environment

    This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”.
    FREE! Go There Now!


    NEW! Test terminal-based applications with Rational Functional Tester

    Regression testing -- in which code is thoroughly tested to ensure that changes have not produced unexpected results -- is an important part of any development process. But many testing environments neglect the terminal-based applications that still form the backbone of many industries. In this tutorial, you'll learn how the Rational Functional Tester Extension for Terminal-Based Applications works with other Rational Functional Tester to help test terminal-based applications quickly and easily.
    FREE! Go There Now!


    NEW! Try IBM Rational Asset Manager V7.0 online!

    You can now evaluate IBM Rational Asset Manager V7.0 online without installing or configuring it on your own system! Rational Asset Manager helps create, modify, govern, find, and reuse any type of development assets, including SOA and systems development assets. Rational Asset Manager helps you reduce software development costs and improve quality by facilitating the reuse of all types of software development-related assets. Visit developerWorks to learn more about this product and register to explore its capabilities online.
    FREE! Go There Now!


    NEW! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    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-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT