Advanced email in PHP

Ok I extracted the zip file…now what do i do? I see 9 PHP files, jumping off a ladder looks easier at this stage

Here’s the same code without all of the author’s commentary. Just make a form and insert the $_POST variables from the form into the strings that get passed to the object’s methods where appropriate.


<?php
require_once("htmlMimeMail5.php");

$mail = new htmlMimeMail5();
$mail->setFrom("Richard <richard@example.com>");
$mail->setSubject('Test email');
$mail->setPriority('high');
$mail->setText('Sample text');
$mail->setHTML('<body background="background.gif"><b>Sample HTML</b></body>');
$mail->addEmbeddedImage(new fileEmbeddedImage('background.gif', 'image/gif', new Base64Encoding()));
$mail->addAttachment(new fileAttachment('example.zip', 'application/zip', new Base64Encoding()));
$mail->send(array('richard@example.com'));

?>

Just make a form and insert the $_POST variables from the form into the strings that get passed to the object’s methods where appropriate.

[B]Easier said than done, Im not familar with this method

Compared with the example I was using this is totally different, how does the attachment get attached?[/B]

Put the 9 files in a new folder in your document root and put require(‘/whatever/the/folder/is/called/htmlMimeMail.php’) in your script.

Like this:


...
$mail->setFrom($_POST['from']);
$mail->setSubject($_POST['subject']);
...
$mail->addAttachment(new fileAttachment($_FILES['fileatt']['name'],$_FILES['fileatt']['type'], new Base64Encoding()));
...

except you would probably need to use move_uploaded_file() to move the files to your document root first and put in that filename because PHP can only find it by tmp_name if it’s still in the /tmp folder.

Actually, for PHP 4.3.2 you can do this:


$attachment = $mail->getFile($_FILES['fileatt']['tmp_name']);
$mail->addAttachment($attachment,$_FILES['fileatt'['name'],$_FILES['fileatt']['type']);

The addAttachment and addHtmlImage methods changed in version 5.

So PHP would be:


<?php 
require_once("htmlMimeMail5.php"); 

$mail = new htmlMimeMail5(); 
$mail->setFrom("Richard <richard@example.com>"); 
$mail->setSubject('Test email'); 
$mail->setPriority('high'); 
$mail->setText('$to, $from'); 
$mail->setHTML('$enquiry, $id, $etc'<b>Sample HTML</b></body>'); 
$mail->addEmbeddedImage(new fileEmbeddedImage('background.gif', 'image/gif', new Base64Encoding())); 
$mail->addAttachment(new fileAttachment($_FILES['fileatt']['name'],$_FILES['fileatt']['type'], new Base64Encoding())); 
$mail->send(array('richard@example.com')); 

?> 

And HTML would be


<html>
<head>
<title>Send an Email</title>
</head>
<body>
<h1>Send an Email</h1>
<form action="htmlmimemail.php" method="POST" enctype="multipart/form-data">
<p>To: <input type="text" name="to" value="" /><br />
From: <input type="text" name="from" value="" /><br />
Subject: <input type="text" name="subject" value="" /></p>
<p>Message:<br />
<textarea cols="70" rows="20" name="message"></textarea></p>
<p>File Attachment 1: <input type="file" name="fileatt" /></p>
<p><input type="submit" value="Send" /></p>
</form>
</body>
</html>

???

No. You need to get version 2.5.1. htmlMimeMail5 is for PHP 5. You need to require() it in your own script, not make it the form action. Then catch up on my last few posts where I explained passing the $_POST variables to the mail methods.

It’s 2:30 AM here, so I’m gonna call it a night. I’ll check in tomorrow and see how you’re doing. :slight_smile:

Great email tut.

Thanx

Awesome tutorial. Just what I needed. I’m really glad you mentioned that you can use your ISP’s SMTP server if running a server from home.

Thanks

One caveat to all of this is that you will probably find that you need to have
\r as the header separator if the script is hosted on a Windows box. This caught me out on one customer.

Hi there, great tutorial! Was wondering if anyone has tried the multiple file upload suggestion?

Hi Guys,

Great tutorial and have got mine working, but is there any way that the email will let you send an attachment that is more than 1 meg? If it’s over 1 meg my page just throws a wobbily and kicks you out when you hit submit? Can it be created to send several meg for example?

Thanks

Chris

The email attachment size limit has more to do with the settings on your email client than with this script.

How to read contents of the email, when u receive an email…

Hi Guys,

This is strange. I’ve got it working now so it sends anything under 1mb with an attachment.

But it it’s over 1mb there is no attachment and there is nothing with the email - even though it takes ages to go when you press the send button?

Any ideas thanks?


<html>
<head>
<title>Send us your design brief</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="main.css">
</head>

<body bgcolor="#FFFFFF">
<form action="mail.php" method="POST" enctype="multipart/form-data">
  <table width="80%" border="0" align="center" class="dotted" height="677">
    <tr>
      <td> 
        <p>&nbsp;</p>
        <table width="94%" cellspacing="0" cellpadding="0" align="center">
          <tr> 
            <th colspan="5" background="images/top.jpg"> 
              <div align="left"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><b><img src="images/design_3.jpg" width="717" height="46"> 
                </b></font></div>
            </th>
          </tr>
          <tr valign="top"> 
            <td rowspan="4" width="26%"> 
              <table width="100%" border="0" cellspacing="1" cellpadding="1">
                <tr> 
                  <td class="maintext"><img src="images/1.gif" width="114" height="24"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><b> 
                    </b></font></td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>1a. 
                    Your Name:</b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <input type="text" name="your_name" class="box" size="20" value="" />
                  </td>
                </tr>
                <tr> 
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>1b. 
                    Centre (ie Paisley etc)</b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <input type="text" name="your_centre" class="box" size="20" value="" />
                  </td>
                </tr>
                <tr> 
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>1c. 
                    Your Telephone</b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <input type="text" name="your_telephone" class="box" size="20" value="" />
                  </td>
                </tr>
                <tr> 
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td><font size="3"><b><font face="Arial, Helvetica, sans-serif">1d. 
                    Your Email</font></b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <input type="text" name="from" class="box" size="20" value="" />
                  </td>
                </tr>
                <tr> 
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td><img src="images/2.gif" width="176" height="24"></td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>2a. 
                    Client name:</b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <input type="text" name="client_name" class="box" size="20" value="" />
                  </td>
                </tr>
                <tr> 
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>2b. 
                    Client history</b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <table width="80%" border="0" cellspacing="0" cellpadding="0" class="box">
                      <tr> 
                        <td colspan="2" valign="top" height="22"> 
                          <input type="radio" name="client" value="Current Client">
                          Current Client <br>
                          <input type="radio" name="client" value="New Client">
                          New Client <br>
                          <input type="radio" name="client" value="Prospective Client">
                          Prospective Client</td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
            <td rowspan="4" width="1%"><img src="blank.gif" width="15" height="30"></td>
            <td rowspan="4" width="32%"> 
              <table width="100%" border="0" cellspacing="1" cellpadding="1">
                <tr> 
                  <td class="maintext"><img src="images/3.gif" width="186" height="24"></td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>3a. 
                    Sizes required</b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <input type="text" name="sizes_required" class="box" size="20" value="" />
                  </td>
                </tr>
                <tr> 
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>3b. 
                    Proof required by</b></font></td>
                </tr>
                <tr> 
                  <td> 
                    <input type="text" name="proof_required_by" class="box" size="20" value="" />
                  </td>
                </tr>
                <tr> 
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td><font face="Arial, Helvetica, sans-serif" size="3"><b>3c. 
                    Colour specification</b></font></td>
                </tr>
                <tr> 
                  <td height="60">
                    <table width="80%" border="0" cellspacing="0" cellpadding="0" class="box">
                      <tr> 
                        <td colspan="2"> 
                          <div align="left"> 
                            <input type="radio" name="colour" value="Mono">
                            Mono</div>
                          <div align="left"> 
                            <input type="radio" name="colour" value="Spot Colour">
                            Spot Colour</div>
                          <div align="left"> 
                            <input type="radio" name="colour" value="Full Colour">
                            Full Colour</div>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
                <tr> 
                  <td height="6">&nbsp;</td>
                </tr>
                <tr> 
                  <td> 
                    <p><font face="Verdana, Arial, Helvetica, sans-serif" size="3"><b><font face="Arial, Helvetica, sans-serif">3d. 
                      Please attach any documents:</font></b></font> </p>
                    <p> 
                      <input type="file" name="fileatt" />
                      <input type="file" name="fileatt2" />
                      <input type="file" name="fileatt3" />
                    </p>
                    </td>
                </tr>
                <tr>
                  <td>&nbsp;</td>
                </tr>
                <tr> 
                  <td height="27"><font face="Verdana, Arial, Helvetica, sans-serif" size="3"><b><font face="Arial, Helvetica, sans-serif">3e. 
                    I have attached the following:</font></b></font></td>
                </tr>
                <tr valign="top"> 
                  <td height="176"> 
                    <table width="80%" border="0" cellspacing="0" cellpadding="0" class="box">
                      <tr> 
                        <td width="10%" valign="top"> 
                          <input type="checkbox" name="artwork_and_logos_attached" value="Yes" />
                        </td>
                        <td width="90%" class="small_text"> 
                          <div align="left">Artwork/Logos</div>
                        </td>
                      </tr>
                      <tr> 
                        <td width="10%" valign="top"> 
                          <input type="checkbox" name="previous_ad_attached" value="Yes" />
                        </td>
                        <td width="90%" class="small_text"> 
                          <div align="left">Previous Ad</div>
                        </td>
                      </tr>
                      <tr> 
                        <td width="10%" valign="top"> 
                          <input type="checkbox" name="rough_outline_attached" value="Yes" />
                        </td>
                        <td width="90%" class="small_text"> 
                          <div align="left">Rough Outline</div>
                        </td>
                      </tr>
                      <tr> 
                        <td width="10%" valign="top"> 
                          <input type="checkbox" name="hard_copy_reference_attached" value="Yes" />
                        </td>
                        <td width="90%" class="small_text">Hard Copy Reference</td>
                      </tr>
                      <tr> 
                        <td width="10%" valign="top" height="8"> 
                          <input type="checkbox" name="other_attached" value="Yes">
                        </td>
                        <td width="90%" class="small_text" height="8">Other - 
                          Please include details </td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
            <td rowspan="4" width="1%"><img src="blank.gif" width="15" height="30"></td>
            <td rowspan="4" width="40%"> 
              <table width="100%" border="0" cellspacing="1" cellpadding="1">
                <tr valign="top"> 
                  <td class="maintext" height="2"><img src="images/4.gif" width="138" height="24"></td>
                </tr>
                <tr valign="top"> 
                  <td height="2"><font face="Arial, Helvetica, sans-serif" size="3"><b>Please 
                    specify any other information you think may be useful to the 
                    designer e.g. company colours (Pantone colours etc.), imagery, 
                    service company provides, brief history of relationship with 
                    us, client website address etc.</b></font></td>
                </tr>
                <tr valign="top"> 
                  <td class="maintext" height="408"> 
                    <div align="center"> 
                      <textarea name="other_details" class="box" cols="32" rows="19" /></textarea>
                      <br>
                      <br>
                      <input type="submit" name="Submit" value="Submit form" class="buttons">
                      <input type="reset" name="Submit2" value="Reset form" class="buttons">
                    </div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr valign="top"></tr>
          <tr valign="top"></tr>
          <tr> </tr>
        </table>
        <br>
        <table width="72%" cellspacing="0" cellpadding="0" align="center">
        </table>
        <table width="94%" border="0" cellspacing="1" cellpadding="1" align="center" background="images/bottom_bit.jpg">
          <tr> 
            <td> 
              <div align="left"><img src="images/bottom.jpg" width="285" height="48" border="0"></div>
            </td>
          </tr>
        </table>
        <br>
      </td>
    </tr>
  </table>
  <p>&nbsp;</p>
</form>
<font size="1" face="Verdana, Arial, Helvetica, sans-serif"><b> </b></font> 
</body>
</html>

php mail code:


<html> 
<head> 
<title> Sending Email </title> 
</head> 
<body> 
<?php 
// Read POST request params into global vars 

$to      = $_POST['to']; 
$from    = $_POST['from']; 
$subject = $_POST['subject']; 

$to="me@me.co.uk"; 
$subject="Design Request form"; 
$your_name = $_POST['your_name']; 
$your_centre = $_POST['your_centre']; 
$your_telephone = $_POST['your_telephone']; 
$client_name = $_POST['client_name']; 
$client = $_POST['client']; 
$sizes_required = $_POST['sizes_required']; 
$proof_required_by = $_POST['proof_required_by']; 
$colour = $_POST['colour']; 
$artwork_and_logos_attached = $_POST['artwork_and_logos_attached']; 
$previous_ad_attached = $_POST['previous_ad_attached']; 
$rough_outline_attached = $_POST['rough_outline_attached'];   
$hard_copy_reference_attached = $_POST['hard_copy_reference_attached']; 
$other_attached = $_POST['other_attached']; 
$other_details = $_POST['other_details']; 

if (!empty($your_name)) { 
$message .= 'Your Name: '. $your_name ."\
\
";
} 
if (!empty($your_centre)) { 
$message .= 'Your Centre: '. $your_centre ."\
\
";
} 
if (!empty($your_telephone)) { 
$message .= 'Your Telephone: '. $your_telephone ."\
\
";
} 
if (!empty($client_name)) { 
$message .= 'Client Name: '. $client_name ."\
\
"; 
} 
if (!empty($client)) { 
$message .= 'Client Type: '. $client ."\
\
";
} 
if (!empty($sizes_required)) { 
$message .= 'Sizes Required: '. $sizes_required ."\
\
";
} 
if (!empty($proof_required_by)) { 
$message .= 'Proof Required by: '. $proof_required_by ."\
\
";
} 
if (!empty($colour)) { 
$message .= 'Advert Colour: '. $colour ."\
\
"; 
} 
if (!empty($artwork_and_logos_attached)) { 
$message .= 'Artwork or Logos attached: '. $artwork_and_logos_attached ."\
\
";
} 
if (!empty($previous_ad_attached)) { 
$message .= 'Previous Ad Attached: '. $previous_ad_attached ."\
\
";
} 
if (!empty($rough_outline_attached)) { 
$message .= 'Rough Outline Attached: '. $rough_outline_attached ."\
\
"; 
} 
if (!empty($hard_copy_reference_attached)) { 
$message .= 'Hard Copy Reference Attached: '. $hard_copy_reference_attached ."\
\
";
} 
if (!empty($other_attached)) { 
$message .= 'Other Attached: '. $other_attached ."\
\
"; 
} 
if (!empty($other_details)) { 
$message .= 'Other details: '. $other_details ."\
\
";
} 


// Obtain file upload vars
$fileatt		= $_FILES['fileatt']['tmp_name'];
$fileatt_type	= $_FILES['fileatt']['type'];
$fileatt_name	= $_FILES['fileatt']['name'];
$fileatt2		= $_FILES['fileatt2']['tmp_name'];
$fileatt_type2	= $_FILES['fileatt2']['type'];
$fileatt_name2	= $_FILES['fileatt2']['name'];
$fileatt3		= $_FILES['fileatt3']['tmp_name'];
$fileatt_type3	= $_FILES['fileatt3']['type'];
$fileatt_name3	= $_FILES['fileatt3']['name'];

$headers = "From: $from";

if (is_uploaded_file($fileatt) || is_uploaded_file($fileatt2) || is_uploaded_file($fileatt3)) {
  // Read the file to be attached ('rb' = read binary)
  if (is_uploaded_file($fileatt)) {
  	$file = fopen($fileatt,'rb');
  	$data = fread($file,filesize($fileatt));
  	fclose($file);

  	// Base64 encode the file data
  	$data = chunk_split(base64_encode($data));
  }

  if (is_uploaded_file($fileatt2)) {
  	$file2 = fopen($fileatt2,'rb');
  	$data2 = fread($file2,filesize($fileatt2));
  	fclose($file2);

  	// Base64 encode the file data
  	$data2 = chunk_split(base64_encode($data2));
  }

  if (is_uploaded_file($fileatt3)) {
  	$file3 = fopen($fileatt3,'rb');
  	$data3 = fread($file3,filesize($fileatt3));
  	fclose($file3);

  	// Base64 encode the file data
  	$data3 = chunk_split(base64_encode($data3));
  }

  // Generate a boundary string
  $semi_rand = md5(time());
  $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
  
  // Add the headers for a file attachment
  $headers .= "\
MIME-Version: 1.0\
" .
              "Content-Type: multipart/mixed;\
" .
              " boundary=\\"{$mime_boundary}\\"";

  // Add a multipart boundary above the plain message
  $message = "This is a multi-part message in MIME format.\
\
" .
             "--{$mime_boundary}\
" .
             "Content-Type: text/plain;\
 charset=\\"iso-8859-1\\"\
" .
             "Content-Transfer-Encoding: 7bit\
\
" .
             $message . "\
\
" .
			 "--{$mime_boundary}\
";

  // Add file attachment(s) to the message
  if ($fileatt_name > "") {
  	$message .= "Content-Type: {$fileatt_type};\
" .
         	     " name=\\"{$fileatt_name}\\"\
" .
            	  "Content-Transfer-Encoding: base64\
" .
           	     "Content-Disposition: attachment;\
" .
           	     " filename=\\"{$fileatt_name}\\"\
\
" .
            	  $data . "\
" .
            	  "--{$mime_boundary}\
";
	}
	
	
  if ($fileatt_name2 > "") {
  	$message .=  "Content-Type: {$fileatt_type2};\
" .
         	     " name=\\"{$fileatt_name2}\\"\
" .
            	  "Content-Transfer-Encoding: base64\
" .
           	     "Content-Disposition: attachment;\
" .
           	     " filename=\\"{$fileatt_name2}\\"\
\
" .
            	  $data2 . "\
" .
            	  "--{$mime_boundary}\
";
	}
	
	
  if ($fileatt_name3 > "") {
  	$message .=  "Content-Type: {$fileatt_type3};\
" .
         	     " name=\\"{$fileatt_name3}\\"\
" .
            	  "Content-Transfer-Encoding: base64\
" .
           	     "Content-Disposition: attachment;\
" .
           	     " filename=\\"{$fileatt_name3}\\"\
\
" .
            	  $data3 . "\
" .
            	  "--{$mime_boundary}";
	}
	$message .=  "--\
\
";	
}

// Send the message
$ok = @mail($to, $subject, $message, $headers);
if ($ok) {
  echo "<p>Thank you.  An email has been sent to our Design Team who will be in touch with you shortly.</p>";
} else {
  echo "<p>Mail could not be sent. Sorry!</p>";
}
?> 
</body>
</html>


Thanks

Hello firends

Good articles about emails in PHP:

http://www.zend.com/zend/spotlight/sendmimeemailpart1.php

I think that ,It was better that article explains more about MIME.

GOOD LUCK!

XPertMailer is a PHP class that you can use to send encoded MIME type e-mail messages (text, HTML, HTML embedded images, attachments) towards a localhost, client or relay SMTP servers with optional authorisation. Cc and Bcc functionality are included.
The XPertMailer class functions are optimised to execute in a very small time and allso to be easy to use. This reduces the size of the code and the time required to write it.
The names of the public functions in the XPertMailer class are eloquent so that they can be used without any confusions being made.
The data sendig is done according to the RFC 821 and RFC 2821, and the message type is in conformity with the RFC 2045, RFC 2046, RFC 2047, RFC 2048, RFC 2049, and RFC 2822.

You can do all you want with a few lines of the code, like this example:

<?php

set_time_limit(0);

// optionaly, you can disable display errors
error_reporting(false); // from php (generally)
define('PRINT_ERROR', false); // from XPertMailer class

// path to XPertMailer class file
require_once 'XPertMailer.php';

/**
 * send to multiple e-mail addresses - text/html format
 * with two HTML embedded images and two attachment files
 * --------------------------------------
 */

// you can optionaly use an relay host name, if fail, send directly to the client
$mail = new XPertMailer(SMTP_RELAY_CLIENT, 'relay-host-name.com');

// set authentication username and password for relay host and auth type (here AUTH_LOGIN, by default is AUTH_DETECT)
$mail->auth('username', 'password', AUTH_LOGIN);

// optionaly, set the port number value for SMTP server socket connections, default are 25
$mail->port(25);

// optionaly, set time out for SMTP server socket connections (in secounds), default are 10
$mail->timeout(30);

// set priority high (default is normal)
$mail->priority(P_HIGH);

// set from mail address and optionaly from name
$mail->from('my@account.com', 'My Name');

// set each header name and value
$header['Cc'] = 'user1@example1.com, anotheruser1@example2.com';
$header['Bcc'] = 'user2@example3.com, anotheruser2@example4.com';
$header['Reply-To'] = 'reply@domain.com';
$header['X-Whatever'] = 'description';

// set additional header informations
$mail->headers($header);

// set HTML embedded images name and optionaly you can rename them
// if the file is not in this directory, write the path name (/path/name.image_extension)
// Attention: do not include path name in the rename file like /path/rename.gif, put only rename.gif
$imgs[] = 'image1.jpg';
$imgs['rename.gif'] = 'image2.gif';

// attach HTML embedded images
$mail->attach($imgs, ATTACH_HTML_IMG);

// set attachment files name and optional you can rename them
// if the file is not in this directory, write the path name (/path/name.file_extension)
$file['new.zip'] = 'archive1.zip';
$file[] = 'archive2.tar.gz';

// attach files
$mail->attach($file, ATTACH_FILE);

// set html value
// Attention: do not include image path name in HTML source like <img src="/path/name.jpg">, put only <img src="name.jpg">
$html = '<!DOCTYPE HTML PUBLIC \\"-//W3C//DTD HTML 4.0 Transitional//EN\\">
<html>
<body>
<img src="image1.jpg" border="0"><br>
<b><u><i>next image</i></u></b> :-)<br>
<img src="rename.gif" border="2"><br>
<font color="red">message html red here</font>
</body>
</html>';

// send to multiple e-mail addresses and optionaly you can set charset value (here UTF-8, by default is ISO-8859-1)
// as you can see, the text/plain message is required because not all mail clients can currently support HTML messages
$send = $mail->send('touser@domain1.com, toanotheruser@domain2.com', 'subject here', 'text version'.CRLF.'new line', $html, 'UTF-8');

// compare the result and print a message
echo $send ? "Done." : "Error.";

// some useful for debugging
echo "<br>Server response: ".$mail->response;

?>

Enjoy :Partydude: www.xpertmailer.com

<self promo>

Here’s some good info about securing forms from email injection attacks: http://www.securephpwiki.com/index.php/Email_Injection