Author Topic: [MOD] Send two part MIME (HTML & Plain Text) Emails  (Read 21829 times)

0 Members and 1 Guest are viewing this topic.

Offline boatman9999

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
[MOD] Send two part MIME (HTML & Plain Text) Emails
« on: June 10, 2005, 01:24:33 PM »
You may wish to send HTML emails to your users, but sending only HTML may not be a good idea as some users email client may reject emails that are not Plain Text.

This [MOD] allows you to send a two part message: - Plain Text and HTML. Email clients configured to show HTML will do so, those which only show Plain Text will show that part of the message.

To install the [MOD]:

Find: includes/email.php and back up the file (eg change the name to email_old.php).

Upload the new includes/email.php

Code: [Select]
<?php

/**************************************************************************
 *                                                                        *
 *    4images - A Web Based Image Gallery Management System               *
 *    ----------------------------------------------------------------    *
 *                                                                        *
 *             File: email.php                                            *
 *        Copyright: (C) 2002 Jan Sorgalla                                *
 *            Email: jan@4homepages.de                                    *
 *              Web: http://www.4homepages.de                             *
 *    Scriptversion: 1.7.1                                                *
 *                                                                        *
 *    Never released without support from: Nicky (http://www.nicky.net)   *
 *                                                                        *
 **************************************************************************
 *                                                                        *
 *    Dieses Script ist KEINE Freeware. Bitte lesen Sie die Lizenz-       *
 *    bedingungen (Lizenz.txt) für weitere Informationen.                 *
 *    ---------------------------------------------------------------     *
 *    This script is NOT freeware! Please read the Copyright Notice       *
 *    (Licence.txt) for further information.                              *
 *                                                                        *
 *************************************************************************/
if (!defined('ROOT_PATH')) {
  die(
"Security violation");
}

class 
Email {

  var 
$auth_type "LOGIN"// Default: "LOGIN". Set to "PLAIN" if required.
  
var $no_error 0;
  var 
$use_smtp;
  var 
$to;
  var 
$subject;
  var 
$body;
  var 
$bcc = array();
  var 
$from "";
  var 
$from_email "";
  var 
$word_wrap 76;
  var 
$template_extension "html";
  var 
$start "{";
  var 
$end "}";
  var 
$key_cache = array();
  var 
$val_cache = array();
  var 
$crlf "\r\n";
 

  function 
Email() {
    global 
$config;
    
$this->use_smtp = ($config['use_smtp'] == 1) ? 0;
    
$this->smtp_auth = (!empty($config['smtp_username']) && !empty($config['smtp_password'])) ? 0;
    
$this->crlf = ($this->use_smtp) ? "\r\n" "\n";
    
$this->mime_boundary "==Multipart_Boundary_".md5(uniqid(time()));
    
$this->html_header "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n<head>\n<meta http-equiv=Content-Type content=\"text/html; charset=\"".$lang['charset']."\">\n";
    
$this->html_footer "</body>\n</html>";

  }

  function 
set_from($email$name "") {
    
$this->from_email $email;
    
$this->from sprintf("Return-Path: %s".$this->crlf$email);
    
$this->from .= ($name != "") ? sprintf("From: %s <%s>".$this->crlf$name$email) : sprintf("From: %s".$this->crlf$email);
  }

  function 
set_to($to) {
    
$this->to $to;
  }

  function 
set_subject($subject) {
    
$this->subject $subject;
  }

  function 
register_vars($var_name$value "") {
    if (!
is_array($var_name)) {
      if (!empty(
$var_name)) {
        
$this->key_cache[$var_name] = "/".$this->add_identifiers($var_name)."/";
        
$this->val_cache[$var_name] = $value;
      }
    }
    else {
      foreach (
$var_name as $key => $val) {
        if (!empty(
$key)) {
          
$this->key_cache[$key] = "/".$this->add_identifiers($key)."/";
          
$this->val_cache[$key] = $val;
        }
      }
    }
  }

  function 
add_identifiers($var_name) {
    return 
preg_quote($this->start.$var_name.$this->end);
  }

  function 
get_template($template$lang) {
    
$path ROOT_PATH."lang/".$lang."/email/".$template.".".$this->template_extension;
    
$line = @implode("", @file($path));
    if (empty(
$line)) {
      
$this->error("Couldn't open Template ".$path);
    }
    return 
$line;
  }

  function 
prepare_text($message) {
    
$message preg_replace("/\r\n/si""\n"$message);
    if (
$this->word_wrap) {
      
$lines explode("\n"$message);
      
$message "";
      for (
$i ;$i sizeof($lines); $i++) {
        
$line_part explode(" "trim($lines[$i]));
        
$buf "";
        for (
$j 0$j count($line_part); $j++)  {
          
$buf_o $buf;
          
$buf .= (($j == 0) ? "" " ").$line_part[$j];
          if (
strlen($buf) > $this->word_wrap && $buf_o != "") {
            
$message .= $buf_o.$this->crlf;
            
$buf $line_part[$j];
          }
        }
        
$message .= $buf.$this->crlf;
      }
    }
    return 
$message;
  }

  function 
set_body($template_name ""$lang "deutsch") {
  
    
$template_name trim($template_name);
    
$body "";
    if (
$template_name != "") {
      
$template $this->get_template($template_name$lang);
      
$body preg_replace($this->key_cache$this->val_cache$template);
      
      if (
$this->send_as_html){
      
$html_body preg_replace("/\r\n/si"""$body);
      
$html_body $this->html_header.$this->email_style."<body>\n".$html_body.$this->html_footer;
      
$text_body strip_tags($body);
         
$body "This is a multi-part message in MIME format.\n\n" .
      
"--{$this->mime_boundary}\n" .
      
"Content-Type: text/plain; charset=\"".$lang['charset']."\"\n" .
      
"Content-Transfer-Encoding: 7bit\n\n" .
      
"{$text_body}\n" .
      
"--{$this->mime_boundary}\n" .
      
"Content-Type: text/html; charset=\"".$lang['charset']."\"\n" .
      
"Content-Transfer-Encoding: 7bit\n\n" .
      
"{$html_body}\n" .
      
"--{$this->mime_boundary}--";
       }
       else {
$body strip_tags($body);
       }
    }
    
$this->body = ((!empty($this->body)) ? $this->body "").$this->prepare_text($body);
  }

  function 
set_simple_body($body "") {
    
$this->body = ((!empty($this->body)) ? $this->body "").$this->prepare_text($body);
  }

  function 
set_bcc($bcc) {
    foreach (
$bcc as $val) {
      
$val trim($val);
      if (
preg_match('/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+@([-0-9A-Z]+\.)+([0-9A-Z]){2,4}$/i'$val)) {
        
$this->bcc[] = $val;
      }
    }
  }

  function 
create_header() {
    global 
$config;
    
    
    
    
$header "";
         
    if (empty(
$this->from)) {
      
$header .= sprintf("Return-Path: %s\r\n"$config['site_email']);
      
$header .= sprintf("From: %s\r\n"$config['site_email']);
    }
    else {
      
$header .= $this->from;
    }
        
    if (!empty(
$this->bcc) && !$this->use_smtp) {
      
$bcc_list "";
      foreach (
$this->bcc as $key => $val) {
        
$bcc_list .= (($bcc_list != "") ? ", " "").$val;
      }
      
$header .= sprintf("Bcc: %s\r\n"$bcc_list);
    }
    
//$header .= sprintf("Subject: %s\r\n", $this->subject);
    
$header .= "Date: " date("r") ."\r\n";
    
    
if ($this->send_as_html){ 
    
$header .= "MIME-Version: 1.0\r\n" .
      
"Content-Type:multipart/alternative;\n" .
      
" boundary=\"{$this->mime_boundary}\"\r\n";
      
}
        
    return 
$header;
  }

  function 
send_email() {
    if (
$this->use_smtp) {
      return (
$this->smtp_mail($this->to$this->subject$this->body$this->create_header())) ? 0;
    }
    else {
      return (
mail($this->to$this->subject$this->body$this->create_header())) ? 0;
      
      
//echo $this->send_as_html;
      
      //exit;
    
}
  }

  function 
smtp_mail($mail_to$subject$body$headers "") {
    global 
$config;
    
$ok 1;

    if (empty(
$config['smtp_host'])) {
      
$config['smtp_host'] = "localhost";
    }

    
// open socket.
    
$fp fsockopen($config['smtp_host'], 25);
    
$result fgets($fp1024);
    if (
substr($result03) != 220) {
      
$ok 0;
      
$this->error("Invalid mail server response (service not ready?): $result"1);
    }

    
// send helo
    
if ($this->smtp_auth) {
      
fputs($fp"EHLO ".$config['smtp_host'].$this->crlf);

      
/**
       * Patch by forum user blueshift. Thanks!
       */

      // not ok until first valid server response
      
$ok 0;

      
// fetch response line after line
      
while (!feof($fp)) {
        
$result fgets($fp1024);
        if (
strlen($result)!=0) {
          if (
substr($result03) == 250) {
            
$ok 1;
            
// lower timeout after first valid response
            
if (function_exists('stream_set_timeout')) {
              
stream_set_timeout($fp1);
            }
          }
          else {
            
// reset ok on error
        $ok 0;
            break;
          }
    }
        else {
          
// EOF
          
break;
    }
      }

      if (
$ok == 0) {
        
$this->error("EHLO invalid mail server response: $result"1);
      }

      if (
function_exists('stream_set_timeout')) {
        
// reset timeout for subsequent ops
        
stream_set_timeout($fp30);
      }

      if (
strtoupper($this->auth_type) == "PLAIN") {
        
fputs($fp"AUTH PLAIN ".base64_encode($config['smtp_username'].chr(0).$config['smtp_password']).$this->crlf);
        
$result fgets($fp1024);
        if (
substr($result03) != 235) {
          
$ok 0;
          
$this->error("AUTH PLAIN invalid mail server response: $result<br /> Maybe your SMTP Server does'nt support authentification. Try to leave Username and Password blank in your settings."1);
        }
      }
      else {
        
fputs($fp"AUTH LOGIN".$this->crlf);
        
$result fgets($fp1024);
        if (
substr($result03) != 334) {
          
$ok 0;
          
$this->error("AUTH LOGIN invalid mail server response: $result<br /> Maybe your SMTP Server does'nt support authentification. Try to leave Username and Password blank in your settings."1);
        }

        
fputs($fpbase64_encode($config['smtp_username']).$this->crlf);
        
$result fgets($fp1024);
        if (
substr($result03) != 334) {
          
$ok 0;
          
$this->error("USERNAME invalid mail server response: $result"1);
        }

        
fputs($fpbase64_encode($config['smtp_password']).$this->crlf);
        
$result fgets($fp1024);
        if (
substr($result03) != 235) {
          
$ok 0;
          
$this->error("PASSWORD invalid mail server response: $result"1);
        }
      }
    }
    else {
      
fputs($fp"HELO ".$config['smtp_host'].$this->crlf);
      
$result fgets($fp1024);
      if (
substr($result03) != 250) {
        
$ok 0;
        
$this->error("HELO invalid mail server response: $result"1);
      }
    }

    
// MAIL FROM
    
if (empty($this->from_email)) {
      
$this->from_email $config['site_email'];
    }
    
fputs($fp"MAIL FROM: ".$this->from_email.$this->crlf);
    
$result fgets($fp1024);
    if (
substr($result03) != 250) {
      
$ok 0;
      
$this->error("MAIL FROM invalid mail server response: $result"1);
    }

    
// RCPT TO
    
$mail_to_array explode(","$mail_to);
    
$to_header "To: ";
    foreach (
$mail_to_array as $key => $val) {
      
$val trim($val);
      
fputs($fp"RCPT TO: <$val>".$this->crlf);
      
$result fgets($fp1024);
      if (
substr($result03) != 250) {
        
$ok 0;
        
$this->error("RCPT TO invalid mail server response: $result"1);
      }
      
$to_header .= "<$val>, ";
    }
    
$to_header ereg_replace(", $"""$to_header);

    if (!empty(
$this->bcc)) {
      foreach (
$this->bcc as $key => $val) {
        
fputs($fp"RCPT TO: <$val>".$this->crlf);
        
$result fgets($fp1024);
        if (
substr($result03) != 250) {
          
$ok 0;
          
$this->error("RCPT TO invalid mail server response: $result"1);
        }
        
//$to_header .= "<$val>, ";
      
}
      
//$to_header = ereg_replace(", $", "", $to_header);
    
}

    
// DATA
    
fputs($fp"DATA".$this->crlf);
    
$result fgets($fp1024);
    if (
substr($result03) != 354) {
      
$ok 0;
      
$this->error("DATA invalid mail server response: $result"1);
    }

    
// Send subject
    
fputs($fp"Subject: $subject".$this->crlf);

    
// Send headers
    
fputs($fp$to_header.$this->crlf);
    
$headers preg_replace("/([^\r]{1})\n/""\\1\r\n"$headers);
    
fputs($fp$headers.$this->crlf.$this->crlf);

    
// Send body
    
$body preg_replace("/([^\r]{1})\n/""\\1\r\n"$body);
$body preg_replace("/\n\n/""\n\r\n"$body);
$body preg_replace("/\n\./""\n.."$body);
    
fputs($fp$body.$this->crlf);

    
// End of DATA: CRLF.CRLF
    
fputs($fp$this->crlf.".".$this->crlf);
    
$result fgets($fp1024);
    if (
substr($result03) != 250) {
      
$ok 0;
      
$this->error("DATA(end): invalid mail server response: $result"1);
    }

    
// QUIT
    
fputs($fp"QUIT".$this->crlf);
    
$result fgets($fp1024);
    if (
substr($result03) != 221) {
      
$ok 0;
      
$this->error("QUIT: invalid mail server response: $result"1);
    }

    
// Close connection
    
fclose($fp);

    return 
$ok;
  }

  function 
reset($reset_template_vars 0) {
    
$this->to "";
    
$this->subject "";
    
$this->body "";
    
$this->bcc = array();
    
$this->from "";
    
$this->from_email "";
    if (
$reset_template_vars) {
      
$this->key_cache = array();
      
$this->val_cache = array();
    }
  }

  function 
error($errmsg$halt 0) {
    if (!
$this->no_error) {
      echo 
"<br /><font color='#FF0000'><b>Email Error</b></font>: ".$errmsg."<br />";
      if (
$halt) {
        exit;
      }
    }
  }
  
  function 
set_send_html($style_file "") {
    
$style_file trim($style_file);
    
$style_file TEMPLATE_PATH."/".$style_file.".css";
       
    if (
file_exists($style_file)) {
      
      
$this->email_style "<STYLE TYPE=\"text/css\">\n"implode(''file($style_file)) ."</STYLE>\n";
    }
    
$this->send_as_html 1;
  }   

  
  
// end of class
?>



This new script should work as the 'old' script unless you trigger the need to send a two part message. This is done by adding
Code: [Select]
$site_email->set_send_html("email_style");

to any other script calling the email.php class. This line MUST be added before any line setting the body of the email eg:
Code: [Select]
$site_email->set_send_html("email_style");
$site_email->set_body("val_rej_email", $config['language_dir']);

The argument "email_style" defines the css file used to specify the style of the email. This can be any name you choose, or may be left out eg:
Code: [Select]
$site_email->set_send_html("my_own_style");
or,
$site_email->set_send_html();
If argument is set, a file of that name containing standard css should be created, and saved in the relevant templates folder. The filetype should be css, eg email_style.css

An example css file would be:
Code: [Select]
body {
background:#FFFFFF;
color:#283840;
font:12px/14px verdana, arial, helvetica, sans serif;
}

td.message {
border: 1px solid #C0DFED;
padding: 0px 5px 0px 5px;
background-color: #F6FBFD;

}
ul, li, p,td {
color: #000000;
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
line-height : 14px;
background-color : transparent;
}
p.smalltext {
font-family: Tahoma,Verdana,Arial,Helvetica,sans-serif;
font-size: 11px;
font-weight: normal;
background-color : transparent;
}

The script has been tested with the php mail() function, but has not been tested with SMTP.

Different email clients display css in theirr own way (I understand that Hotmail does not display CSS html at all), so you may get varying results fro those you expect.

Now add HTML tags to your email template(s), found in lang/{your lang}/email. These tags are removed by the script to send the Plain Text part of the message.

Experiment and enjoy!

Note: Code updated 12/06/2005

Offline V@no

  • If you don't tell me what to do, I won't tell you where you should go :)
  • Global Moderator
  • 4images Guru
  • *****
  • Posts: 17.849
  • mmm PHP...
    • View Profile
    • 4images MODs Demo
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #1 on: June 10, 2005, 03:00:45 PM »
Very nice!

I've spoted two things, though:

1) you are forcing to send email in iso-8859-1 encoding but IMO it should be based on $lang['charset'] of the language its being send in.
2) because you are using file_get_contents() function, this mod will not work on servers with PHP version below 4.3.0 unless u add in includes/functions.php something like this:
Code: [Select]
if(!function_exists('file_get_contents'))
{
  function file_get_contents($file)
  {
    $file = file($file);
    return !$file ? false : implode('', $file);
  }
}
Your first three "must do" before you ask a question:
Please do not PM me asking for help unless you've been specifically asked to do so. Such PMs will be deleted without answer. (forum rule #6)
Extension for Firefox/Thunderbird: Master Password+    Back/Forward History Tweaks (restartless)    Cookies Manager+    Fit Images (restartless for Thunderbird)

Offline boatman9999

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #2 on: June 10, 2005, 07:00:08 PM »
Thanks V@no. Very helpful as always. Will change the code when I get the time.

Offline boatman9999

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #3 on: June 12, 2005, 12:14:03 PM »
Code updated.

b.o.fan

  • Guest
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #4 on: June 12, 2005, 12:22:48 PM »

This new script should work as the 'old' script unless you trigger the need to send a two part message. This is done by adding
Code: [Select]
$site_email->set_send_html("email_style");

to any other script calling the email.php class. This line MUST be added before any line setting the body of the email eg:
Code: [Select]
$site_email->set_send_html("email_style");
$site_email->set_body("val_rej_email", $config['language_dir']);

The argument "email_style" defines the css file used to specify the style of the email. This can be any name you choose, or may be left out eg:
Code: [Select]
$site_email->set_send_html("my_own_style");
or,
$site_email->set_send_html();
If argument is set, a file of that name containing standard css should be created, and saved in the relevant templates folder. The filetype should be css, eg email_style.css

An example css file would be:
Code: [Select]
body {
background:#FFFFFF;
color:#283840;
font:12px/14px verdana, arial, helvetica, sans serif;
}

td.message {
border: 1px solid #C0DFED;
padding: 0px 5px 0px 5px;
background-color: #F6FBFD;

}
ul, li, p,td {
color: #000000;
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
line-height : 14px;
background-color : transparent;
}
p.smalltext {
font-family: Tahoma,Verdana,Arial,Helvetica,sans-serif;
font-size: 11px;
font-weight: normal;
background-color : transparent;
}

The script has been tested with the php mail() function, but has not been tested with SMTP.

Different email clients display css in theirr own way (I understand that Hotmail does not display CSS html at all), so you may get varying results fro those you expect.

Now add HTML tags to your email template(s), found in lang/{your lang}/email. These tags are removed by the script to send the Plain Text part of the message.

Experiment and enjoy!

Note: Code updated 12/06/2005


where i must add this??? it not easy to follow your desciption... :(

b.o.fan

Offline boatman9999

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #5 on: June 12, 2005, 03:37:57 PM »
Sorry if it's confusing. You ask  where do I add this?, where do you add what?

A bit more explaination for the [MOD]:

Step 1. Replace the file includes/email.php with the new one above.

Step 2. Find a script which is sending emails for you (eg member.php).

Step 3. Find in that script any line containing
Code: [Select]
$site_email->set_body............Step 4. If you want to send HTML email then add above each of those lines:
Code: [Select]
$site_email->set_send_html("email_style"); where (if you want to) "email_style" is the name of your css style file. if you don't want to use a css file then add above the line
in Step 3,
Code: [Select]
$site_email->set_send_html();
Step 5. Optional. Create a css style file with name "email_style" (or any other name but the same as you are referring to in Step 4) and save this in your relevant templates folder. The file should have the file extension css.

Step 6. Go to the email template(s) in lang/{your lang}/email folder open a relevant template file, add HTML tags to the lines in that template. Save the amended template file. Repeat for other templates as required.

Hope this helps?

Offline ascanio

  • Hero Member
  • *****
  • Posts: 569
    • View Profile
    • http://www.surfourspace.net
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #6 on: March 28, 2006, 10:52:58 PM »
Hi im trying to send html on my email and i add this code to the email and it doesn't show up:

Code: [Select]
<img src="http://mydomain.com/myimage.jpg">

Offline boatman9999

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #7 on: April 03, 2006, 06:57:34 PM »
Hi,

Where are you adding the code:
Code: [Select]
<img src="http://mydomain.com/myimage.jpg">?

Offline ascanio

  • Hero Member
  • *****
  • Posts: 569
    • View Profile
    • http://www.surfourspace.net
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #8 on: April 03, 2006, 07:04:49 PM »

Offline boatman9999

  • Jr. Member
  • **
  • Posts: 50
    • View Profile
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #9 on: April 04, 2006, 07:28:27 PM »
Hi,

Do you have success in sending your emails in two parts (HTML & plain text) except for the <img> tag?

That is;  does everything in the MOD work OK and as it should, except for displaying images?

Offline ascanio

  • Hero Member
  • *****
  • Posts: 569
    • View Profile
    • http://www.surfourspace.net
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #10 on: April 06, 2006, 09:09:34 PM »
i think the only hink is working is the break line <br> tag

Offline thunderstrike

  • 4images Guru
  • *******
  • Posts: 2.327
    • View Profile
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #11 on: November 04, 2007, 04:45:08 PM »
I no see this topic before ...  8O

One bug I find -

Quote
function Email() {
    global $config;

replace:

Code: [Select]
function Email() {
    global $config, $lang;

Well - I create too -

http://www.4homepages.de/forum/index.php?topic=18744.0

;)
8 steps need when ask question -

- PHP version (ACP - > phpinfo())
- mySQL version (ACP - > phpinfo())
- 4images version
- Post screenshot / URL
- Post code in BB Code (no need full file for code) or post attach file
- It doesn't work. What is say - what is do for no work
- Install MOD ? If so - please say (troubleshooting)
- Read FAQ ? Install Bug fixes ?

Offline 4imageUSER

  • Pre-Newbie
  • Posts: 1
    • View Profile
Re: [MOD] Send two part MIME (HTML & Plain Text) Emails
« Reply #12 on: June 09, 2011, 08:27:26 PM »
is there a way to have the postcard "in html" in the email. i would like to send a postcard in the email. not a link to a postcard. is there a way to do that?

thanks