Platform  3.1
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
sendmail.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @license http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Anakeen - licence CC
5  * @package FDL
6 */
7 /**
8  * Send document mail with SMTP protocol
9  *
10  * @author Anakeen 2007
11  * @version $Id: sendmail.php,v 1.4 2007/10/10 16:15:35 eric Exp $
12  * @license http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ Anakeen - licence CC
13  * @package FDL
14  * @subpackage
15  */
16 /**
17  */
18 include ('Mail/mime.php');
19 include ('Net/SMTP.php');
20 /**
21  * Send mail via smtp server
22  * @param string $to mail addresses (, separate)
23  * @param string $cc mail addresses (, separate)
24  * @param string $bcc mail addresses (, separate)
25  * @param string $from mail address
26  * @param string $subject mail subject
27  * @param Mail_mime &$mimemail mail mime object
28  * @return string error message : if no error: empty if no error
29  */
30 function sendmail($to, $from, $cc, $bcc, $subject, &$mimemail, $multipart = null)
31 {
32 
33  $rcpt = array_merge(explode(',', $to) , explode(',', $cc) , explode(',', $bcc));
34 
35  $host = getParam('SMTP_HOST', 'localhost');
36  $port = getParam('SMTP_PORT', 25);
37  $login = getParam('SMTP_LOGIN');
38  $password = getParam('SMTP_PASSWORD');
39 
40  if (is_a($mimemail, 'Mail_Mime')) {
41  $mimemail->setFrom($from);
42  if ($cc != '') $mimemail->addCc($cc);
43  }
44 
45  $xh['To'] = $to;
46  /* Create a new Net_SMTP object. */
47  if (!($smtp = new Net_SMTP($host, $port))) {
48  die("Unable to instantiate Net_SMTP object\n");
49  }
50  $smtp->setDebug(false);
51  /* Connect to the SMTP server. */
52  if (PEAR::isError($e = $smtp->connect())) {
53  return ("smtp connect:" . $e->getMessage());
54  }
55 
56  if ($login) {
57  if (PEAR::isError($e = $smtp->auth($login, $password))) {
58  return ("smtp login:" . $e->getMessage());
59  }
60  }
61  /* Send the 'MAIL FROM:' SMTP command. */
62  $smtp_from = $from;
63  if( preg_match('/<(?<from>[^>]*)>/', $from, $reg) ) {
64  $smtp_from = $reg['from'];
65  }
66  if (PEAR::isError($smtp->mailFrom($smtp_from))) {
67  return ("Unable to set sender to <$smtp_from>");
68  }
69  /* Address the message to each of the recipients. */
70  foreach ($rcpt as $v) {
71  $v = trim($v);
72  if ($v) {
73  if (preg_match("/<([^>]*)>/", $v, $reg)) {
74  $v = $reg[1];
75  }
76  if (PEAR::isError($res = $smtp->rcptTo($v))) {
77  return ("Unable to add recipient <$v>: " . $res->getMessage());
78  }
79  }
80  }
81  setlocale(LC_TIME, 'C');
82 
83  $data = '';
84 
85  if (is_a($mimemail, 'Fdl_Mail_mimePart')) {
86 
87  $mm = new Mail_Mime();
88  $mm->_build_params['head_charset'] = 'UTF-8';
89 
90  $mm->setFrom($from);
91  if ($cc != '') {
92  $mm->addCc($cc);
93  }
94 
95  $email = $mimemail->encode();
96  if (PEAR::isError($email)) {
97  $err = sprintf("Error encoding Fdl_Mail_mimePart : %s", $email->message);
98  error_log(__CLASS__ . "::" . __FUNCTION__ . " " . $err);
99  return $err;
100  }
101 
102  $txtHeaders = $mm->txtHeaders(array_merge($email['headers'], array(
103  'To' => $to,
104  'Subject' => $subject,
105  'Date' => strftime("%a, %d %b %Y %H:%M:%S %z", time()) ,
106  'Message-Id' => sprintf("<%s@%s>", strftime("%Y%M%d%H%M%S-", time()) . rand(1, 65535) , $host) ,
107  'User-Agent' => sprintf("Dynacase Platform %s", getParam('VERSION'))
108  )));
109 
110  $data = $txtHeaders . $mm->_build_params['eol'] . $email['body'];
111  } else {
112 
113  $body = $mimemail->get();
114 
115  $xh['Date'] = strftime("%a, %d %b %Y %H:%M:%S %z", time());
116  // $xh['Content-type']= "multipart/related";
117  $xh['Subject'] = $subject;
118  $xh['Message-Id'] = '<' . strftime("%Y%M%d%H%M%S-", time()) . rand(1, 65535) . "@$host>";
119 
120  $xh['User-Agent'] = sprintf("Dynacase Platform %s", getParam('VERSION'));
121  $data = "";
122  $h = $mimemail->headers($xh);
123  if ($multipart) $h['Content-Type'] = str_replace("mixed", $multipart, $h['Content-Type']);
124 
125  foreach ($h as $k => $v) {
126  $data.= "$k: $v\r\n";
127  }
128 
129  $data.= "\r\n" . $body;
130  }
131  /* Set the body of the message. */
132  if (PEAR::isError($smtp->data($data))) {
133  return ("Unable to send data");
134  }
135  /* Disconnect from the SMTP server. */
136  $smtp->disconnect();
137 }
138 /**
139  * redefine class to add explicit CID
140  */
141 class Fdl_Mail_mime extends Mail_mime
142 {
143  // USE TO ADD CID in attachment
144 
145  /**
146  * Adds a file to the list of attachments.
147  *
148  * @param string $file The file name of the file to attach
149  * OR the file data itself
150  * @param string $c_type The content type
151  * @param string $name The filename of the attachment
152  * Only use if $file is the file data
153  * @param bool $isFilename Whether $file is a filename or not
154  * Defaults to true
155  * @return mixed true on success or PEAR_Error object
156  * @access public
157  */
158  function addAttachment($file, $c_type = 'application/octet-stream', $name = '', $isfilename = true, $encoding = 'base64', $cid = '', $charset = "UTF-8")
159  {
160  $filedata = ($isfilename === true) ? $this->_file2str($file) : $file;
161  if ($isfilename === true) {
162  // Force the name the user supplied, otherwise use $file
163  $filename = (!empty($name)) ? $name : basename($file);
164  } else {
165  $filename = $name;
166  }
167  if (empty($filename)) {
168  return PEAR::raiseError('The supplied filename for the attachment can\'t be empty');
169  }
170  if (PEAR::isError($filedata)) {
171  return $filedata;
172  }
173 
174  $this->_parts[] = array(
175  'body' => $filedata,
176  'name' => $filename,
177  'charset' => $charset,
178  'c_type' => $c_type,
179  'encoding' => $encoding
180  );
181  return true;
182  }
183 
184  function addAttachmentInline($file, $c_type = 'application/octet-stream', $name = '', $isfilename = true, $encoding = 'base64', $cid = '', $charset = "UTF-8")
185  {
186  $filedata = ($isfilename === true) ? $this->_file2str($file) : $file;
187  if ($isfilename === true) {
188  // Force the name the user supplied, otherwise use $file
189  $filename = (!empty($name)) ? $name : basename($file);
190  } else {
191  $filename = $name;
192  }
193  if (empty($filename)) {
194  return PEAR::raiseError('The supplied filename for the attachment can\'t be empty');
195  }
196  if (PEAR::isError($filedata)) {
197  return $filedata;
198  }
199 
200  $this->_parts[] = array(
201  'body' => $filedata,
202  'name' => $filename,
203  'charset' => $charset,
204  'c_type' => $c_type,
205  'encoding' => $encoding,
206  'disposition' => 'inline',
207  'cid' => $cid
208  );
209  return true;
210  }
211  /**
212  * Adds an attachment subpart to a mimePart object
213  * and returns it during the build process.
214  *
215  * @param object The mimePart to add the image to
216  * @param array The attachment information
217  * @return object The image mimePart object
218  * @access private
219  */
220  function &_addAttachmentPart(&$obj, $value)
221  {
222  $params['content_type'] = $value['c_type'];
223  $params['encoding'] = $value['encoding'];
224  $params['dfilename'] = $value['name'];
225  $params['filename'] = $value['name'];
226  $params['charset'] = $value['charset'];
227 
228  if (isset($value['disposition'])) {
229  $params['disposition'] = $value['disposition'];
230  } else {
231  $params['disposition'] = 'attachment';
232  }
233 
234  if (isset($value['cid'])) {
235  $params['cid'] = $value['cid'];
236  }
237 
238  if (isset($value['name_encoding'])) {
239  $params['name_encoding'] = $value['name_encoding'];
240  } else {
241  $params['name_encoding'] = 'quoted-printable';
242  }
243 
244  if (isset($value['filename_encoding'])) {
245  $params['filename_encoding'] = $value['filename_encoding'];
246  } else {
247  $params['filename_encoding'] = 'quoted-printable';
248  }
249 
250  $obj->addSubpart($value['body'], $params);
251  }
252  function __construct($crlf = "\r\n")
253  {
254  parent::Mail_mime($crlf);
255  $this->_build_params['html_charset'] = 'UTF-8';
256  $this->_build_params['text_charset'] = 'UTF-8';
257  $this->_build_params['head_charset'] = 'UTF-8';
258  }
259 }
260 
261 class Fdl_Mail_mimePart extends Mail_mimePart
262 {
263  var $_filename = '';
264 
265  function Fdl_Mail_mimePart($body = '', $params = array())
266  {
267  // Keep track of the unaltered/unencoded filename for further use
268  if (isset($params['filename'])) {
269  $this->_filename = $params['filename'];
270  } elseif (isset($params['dfilename'])) {
271  $this->_filename = $params['dfilename'];
272  }
273 
274  parent::Mail_mimePart($body, $params);
275  }
276 
277  function &addSubpart($body, $params)
278  {
279  if (!property_exists('Mail_mimePart', '_body_file') && isset($params['body_file'])) {
280  // Mail_mimePart < 1.6.0 has no support for passing a file with $param['body_file']
281  $body = file_get_contents($params['body_file']);
282  unset($params['body_file']);
283  }
284  $this->_subparts[] = new Fdl_Mail_mimePart($body, $params);
285  return $this->_subparts[count($this->_subparts) - 1];
286  }
287 
288  function setBodyFile($file)
289  {
290  if (!property_Exists('Mail_mimePart', '_body_file')) {
291  // Mail_mimePart < 1.6.0
292  $this->_body = file_get_contents($file);
293  } else {
294  $this->_body_file = $file;
295  }
296  return $this;
297  }
298 }
299 /**
300  * record message sent from freedom
301  */
302 function createSentMessage($to, $from, $cc, $bcc, $subject, &$mimemail, &$doc = null)
303 {
304  include_once ('WHAT/Lib.Common.php');
305 
306  $msg = createDoc(getDbAccessFreedom() , "SENTMESSAGE", true);
307  if ($msg) {
308  $msg->setValue("emsg_from", $from);
309  $msg->setValue("emsg_date", Doc::getTimeDate());
310  $msg->setValue("emsg_subject", $subject);
311  if ($doc && $doc->id) {
312  $msg->setValue("emsg_refid", $doc->id);
313  $msg->profid = $doc->profid;
314  }
315  $trcp = array();
316  foreach (explode(',', $to) as $v) {
317  if ($v) $msg->addArrayRow("emsg_t_recipient", array(
318  "emsg_sendtype" => "to",
319  "emsg_recipient" => $v
320  ));
321  }
322  foreach (explode(',', $cc) as $v) {
323  if ($v) $msg->addArrayRow("emsg_t_recipient", array(
324  "emsg_sendtype" => "cc",
325  "emsg_recipient" => $v
326  ));
327  }
328  foreach (explode(',', $bcc) as $v) {
329  if ($v) $msg->addArrayRow("emsg_t_recipient", array(
330  "emsg_sendtype" => "bcc",
331  "emsg_recipient" => $v
332  ));
333  }
334 
335  if (is_a($mimemail, 'Fdl_Mail_mimePart')) {
336  // Flatten the MIME parts by expanding and removing the mutipart entities
337  $partList = array(&$mimemail
338  );
339  $i = 0;
340  while ($i < count($partList)) {
341  if (count($partList[$i]->_subparts) <= 0) {
342  $i++;
343  continue;
344  }
345  $multipart = $partList[$i];
346  array_splice($partList, $i, 1);
347  foreach ($multipart->_subparts as & $part) {
348  $partList[] = & $part;
349  }
350  unset($part);
351  }
352  // Search for a text/plain part and extract it
353  $textPart = null;
354  foreach ($partList as $i => & $part) {
355  if (preg_match("|^text/plain|", $part->_headers['Content-Type'])) {
356  $textPart = $part;
357  array_splice($partList, $i, 1);
358  break;
359  }
360  }
361  unset($part);
362  // Search for a text/html part and extract it
363  $htmlPart = null;
364  foreach ($partList as $i => & $part) {
365  if (preg_match("|^text/html|", $part->_headers['Content-Type'])) {
366  $htmlPart = $part;
367  array_splice($partList, $i, 1);
368  break;
369  }
370  }
371  unset($part);
372  // Store the text part
373  $textBody = '';
374  if ($textPart !== null) {
375  if ($textPart->_body_file != '') {
376  $textBody = file_get_contents($textPart->_body_file);
377  } else {
378  $textBody = $textPart->_body;
379  }
380  $msg->setValue('emsg_textbody', $textBody);
381  }
382  // Store the HTML part
383  $htmlBody = '';
384  if ($htmlPart !== null) {
385  if ($htmlPart->_body_file != '') {
386  $htmlBody = file_get_contents($htmlPart->_body_file);
387  } else {
388  $htmlBody = $htmlPart->_body;
389  }
390  $msg->setValue('emsg_htmlbody', $htmlBody);
391  }
392  // Store the remaining parts
393  foreach ($partList as $i => & $part) {
394  $tmpfile = tempnam(getTmpDir() , 'fdl_attach');
395  if ($part->_body_file != '') {
396  copy($part->_body_file, $tmpfile);
397  } else {
398  file_put_contents($tmpfile, $part->_body);
399  }
400  $msg->storeFile('emsg_attach', $tmpfile, $part->_filename, $i);
401  @unlink($tmpfile);
402  }
403  unset($part);
404 
405  $err = $msg->add();
406  if ($err != '') {
407  return $err;
408  }
409 
410  if ($htmlPart !== null && $htmlBody != '') {
411  // Re-link the HTML part CIDs
412  foreach ($partList as $i => & $part) {
413  $cid = preg_replace('/^<(.+)>$/', '\1', $part->_headers['Content-ID']);
414  if ($cid != '') {
415  $htmlBody = str_replace(sprintf("cid:%s", $cid) , $msg->getfileLink('emsg_attach', $i) , $htmlBody);
416  }
417  }
418  unset($part);
419 
420  $msg->disableEditControl();
421  $msg->setValue('emsg_htmlbody', $htmlBody);
422  $err = $msg->modify(true);
423  $msg->enableEditControl();
424 
425  if ($err != '') {
426  return $err;
427  }
428  }
429 
430  return '';
431  }
432 
433  $msg->setValue("emsg_textbody", $mimemail->_txtbody);
434  $msg->setValue("emsg_htmlbody", $mimemail->_htmlbody);
435  $linkedbody = $mimemail->_htmlbody;
436  foreach ($mimemail->_parts as $k => $v) {
437  $tmpfile = tempnam(getTmpDir() , 'fdl_attach');
438  file_put_contents($tmpfile, $v["body"]);
439  $msg->storeFile("emsg_attach", $tmpfile, $v["name"], $k);
440  @unlink($tmpfile);
441  }
442 
443  $err = $msg->add();
444  // relink body
445  if ($err == "") {
446  $linkedbody = $mimemail->_htmlbody;
447  foreach ($mimemail->_parts as $k => $v) {
448  $linkedbody = str_replace("cid:" . $v["cid"], $msg->getFileLink("emsg_attach", $k) , $linkedbody);
449  }
450  $msg->disableEditControl();
451  $msg->setValue("emsg_htmlbody", $linkedbody);
452  $err = $msg->modify(true);
453  }
454  }
455  return $err;
456 }
457 ?>
← centre documentaire © anakeen - published under CC License - Dynacase