Click here to Skip to main content
13,144,300 members (33,956 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

7.1K views
195 downloads
4 bookmarked
Posted 14 Mar 2017

Send HTML mail with attachments using PHP

, 14 Mar 2017
Rate this:
Please Sign up or sign in to vote.
A PHP object for send HTML mail with attachment.

Introduction

In the development of an Android application I have had the necessity to send data to an Internet application possibly with pictures attached. Send a simple mail or HTML mail with PHP mail function is easy; the same function can accept message with embedded file(s) therefore it is the user who has to prepare the data through appropriate headers and encodings.

After some samples found on the WEB and not working or not generalised, I found a script (tanks to Antoine Bonnefoy) that not only sends file attachments but also can embeds images: this script has been the starting point for create the PHP class object of this article.

The mail object

The mail object is a PHP class with two functions for send a mail: sendMail and sendMailParms; the second is only a wrapper for the first that permits to write the parameters in an array key=> value that are indifferent to the case (and the order).

The syntax for send a mail is: sendMail($to, $from, $subject, $content, $files = '', $cc = '', $bcc = '') or sendMailParms($parms) where $parms can contain from none to all expected parameters:

KeyNote
MailToThe recipient(s)
SubjectThe mail subject
MessageThe message, possibly in HTML format and with images (see below)
FromThe sender
FilesThe files to be attached (see below)
CcThe Carbon copy recipient(s)
BccThe Blind carbon copy

I.e. sometime like this fragment that receive the data from a form that contains fields named Message , MailTo and possibly an uploaded file:

<?php
//	30/12/2016
include 'mailfile.php';
$msg = "";
foreach ($_REQUEST as $key => $value) $$key = $value;
$t = Array("N"=>"Text","H"=>"HTML","HI"=>"HTML with images");
$subject = $t[$type]." mail";
$parms = Array("subject"=>$subject,"mailto"=>$MailTo,"message"=>$Message,"from"=>"sender@mailoffice.it","files"=>$_FILES);
echo mail::sendMailParms($parms);
?>

HTML mail and embedded images

The message is sent as HTML message if it contains HTML tags. For embedded images the tag is the img tag where the src parameter must have the form:

src='cid:filename', cid: (Content-ID) tells the script that filename image is embedded in the mail.

<table>
<tr><td>Condor Informatique - Turin
<td><a href='www.condorinformatique.com' target='_blank'>
<img title='Condor Informatique - Turin' src='cid:images/condor.gif'></a>
<tr><td>Sermig - Turin
<td><a href='www.sermig.org' target='_blank'>
<br><img title='Sermig - ReTe' src='cid:images/sermig.jpg'></a>
<tr><td><img src=cid:images/info.png>See you later alligator<br>El Condor
</table>

Note that filename must contains the path for read the image, but in the mail the path is stripped by the script.

Below is the PHP fragment for find the images contained in the message.

preg_match_all("/(<img .*?>)/i", $content,$out, PREG_PATTERN_ORDER);
$aEmbedFiles = Array();
foreach($out[1] as $cidFile) {
	$doc = new DOMDocument();
	$doc->loadHTML($cidFile);
	$imageTags = $doc->getElementsByTagName('img');
	foreach($imageTags as $tag) {
		$file = $tag->getAttribute('src');
		if (strtolower(substr($file,0,4)) == "cid:") {
			$file = substr($file,4);
			$aEmbedFiles[basename($file)] = $file;
		}
	}
}

The preg_match finds all img tags and stores them in $out array; I used The DOMDocument object of DOM function to extract the property src as it is complicated to extract by regular expression.

Only the file name of images with cid: are stored in the $aEmbedFiles array.

foreach($aEmbedFiles as $key => $value) {
	$content = str_replace($value, $key,$content);	// replace the path/file with file only
}

The fragment code above replace the path/filename with only the filename.

Attach files

The possibly parameter Files is a list of files to upload; it can have three forms[1]:

  1. a file name,
  2. an array of filenames,
  3. an associative array of items uploaded via the HTTP POST (i.e. it can be the same associative array $_FILES).

In the first two cases the function mimeType returns the MIME type of the file, based on the suffix of the file name[2]:

public static function mimeType($fl) {
	$mimeTypes = Array(".doc"=> "application/msword",".jpg"=>"image/jpeg",".gif"=>"image/gif",".zip"=>"application/zip",".pdf"=>"application/pdf");
	$ext = strtolower(strrchr($fl, '.'));
	return (isset($mimeTypes[$ext])) ? $mimeTypes[$ext] : "application/octet-stream";
}

For the third case, the files uploaded, the mime type is stated on: $_FILES[...]['type'].

Using the demo

The demo is a simple html page with a form[3] for send a mail possibly in HTML format and upload a file (limited to the size).

Notes

  1. ^This is an example of polymorphism of a PHP function.
  2. ^Instead of deprecated mime_content_type function and Fileinfo functions that is in library not by default in PHP.
  3. ^The form is generated by my JavaScript Form generator see CodeProject A JavaScript Form Generator, or on my site.
    <div id='result'></div>
    <span id='form' style='visibility:hidden'>
    Form,frm,Test PHP HTML Mailer,echo.php,receiveData,reset;
    T,Message,,251;
    H,MAX_FILE_SIZE;
    File,Attachment,Attachment file,30,.gif,.jpg, .png;
    T,MailTo,Receiver mail address,25;
    R,type,Message type,60,N=Normal,H=HTML,HI=HTML with images;
    B,fg_Cancel,&#x2718;,40,,Cancel Form;
    B,fg_Reset,&#x21B6;,40;
    B,Start,&#x270E;,40,,Go;
    Control,MailTo,Required,mail;
    Defaults,type=N,MAX_FILE_SIZE=5000,Message=See you later alligator\nEl Condor;
    </span>
    ...
    <script type='text/javascript'>
    formGen("result",$("form").innerHTML);
    ...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Member 4206974
Software Developer Condor Informatique
Italy Italy
Computer literacy (software) : Languages: PHP, Javascript, SQL Autoit,Basic4Android; Frameworks: JOOMLA!
Teaching/Training skills on Office, WEB site development and programming languages.
Others : WEB site development.
UNDP Missions
feb – may 2003 Congo DR Bukavu: ground IT computer course
nov 2003 Burundi Bujumbura: Oracle Data Base course
feb 2005 Burundi Bujumbura: JAVA course
mar 2005 Mali Kati: MS Office course
oct 2006 Mali Kati: MS Office course
jun 2006 Burkina Faso Bobo Dioulasso: MS Office course
jun 2007 Burkina Faso Bobo Dioulasso: MS Office course
may 2007 Argentina Olavarria hospital: Internet application for access to medical records
apr 2008 Burkina Faso Ouagadougou: MS ACCESS and dynamic Internet applications
jun 2008 Niger Niamey: analysis of the computing needs of the Niamey hospital
may 2009 Burkina Faso Ouagadougou: MS ACCESS and dynamic Internet applications
oct 2010 Niger Niamey: analysis of the computing needs of the Niamey hospital (following)
Region Piedmont project Evaluation
mar 2006 Burkina Faso, Niger
mar 2007 Benin, Burkina Faso, Niger
sep 2008 Benin, Burkina Faso, Niger
Others
feb 2010 Burundi Kiremba hospital: MS Office course
feb 2011 Congo DR Kampene hospital: MS Office course

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 14 Mar 2017
Article Copyright 2017 by Member 4206974
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid