33 use OAuth\Common\Storage\DoliStorage;
34 use OAuth\Common\Consumer\Credentials;
62 public $mixed_boundary;
63 public $related_boundary;
64 public $alternative_boundary;
65 public $deliveryreceipt;
67 public $atleastonefile;
81 public $errors = array();
121 public $filename_list = array();
125 public $mimetype_list = array();
129 public $mimefilename_list = array();
133 public $cid_list = array();
138 public $image_boundary;
139 public $atleastoneimage = 0;
140 public $html_images = array();
141 public $images_encoded = array();
142 public $image_types = array(
143 'gif' =>
'image/gif',
144 'jpg' =>
'image/jpeg',
145 'jpeg' =>
'image/jpeg',
146 'jpe' =>
'image/jpeg',
147 'bmp' =>
'image/bmp',
148 'png' =>
'image/png',
149 'tif' =>
'image/tiff',
150 'tiff' =>
'image/tiff',
176 public function __construct($subject, $to, $from, $msg, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc =
"", $addr_bcc =
"", $deliveryreceipt = 0, $msgishtml = 0, $errors_to =
'', $css =
'', $trackid =
'', $moreinheader =
'', $sendcontext =
'standard', $replyto =
'', $upload_dir_tmp =
'')
178 global $conf, $dolibarr_main_data_root, $user;
180 dol_syslog(
"CMailFile::CMailfile: charset=".$conf->file->character_set_client.
" from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, replyto=$replyto trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
181 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
185 if (is_array($mimefilename_list)) {
186 foreach ($mimefilename_list as $key => $val) {
193 $this->sendcontext = $sendcontext;
196 $this->sendmode =
'';
197 if (!empty($this->sendcontext)) {
198 $smtpContextKey = strtoupper($this->sendcontext);
200 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
201 $this->sendmode = $smtpContextSendMode;
204 if (empty($this->sendmode)) {
205 $this->sendmode = (!empty($conf->global->MAIN_MAIL_SENDMODE) ? $conf->global->MAIN_MAIL_SENDMODE :
'mail');
211 $this->eol2 =
"\r\n";
212 if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
215 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
219 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
222 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"), 3);
225 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"), 3);
227 if (empty($subject)) {
228 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
229 $this->error =
'ErrorSubjectIsRequired';
233 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
238 if ($msgishtml == -1) {
239 $this->msgishtml = 0;
241 $this->msgishtml = 1;
244 $this->msgishtml = $msgishtml;
247 global $dolibarr_main_url_root;
250 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
251 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
255 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
257 if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) {
258 $this->msgishtml = 1;
262 if ($this->msgishtml) {
266 if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) {
271 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
273 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
274 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
279 if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA)) {
283 if ($resultImageData<0) {
284 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData");
285 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
288 $findimg += $resultImageData;
293 foreach ($this->html_images as $i => $val) {
294 if ($this->html_images[$i]) {
295 $this->atleastoneimage = 1;
296 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
297 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
299 $posindice = count($filename_list);
300 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
301 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
302 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
304 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
307 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
309 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
318 if (is_array($filename_list)) {
319 foreach ($filename_list as $i => $val) {
320 if ($filename_list[$i]) {
321 $this->atleastonefile = 1;
322 dol_syslog(
"CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].
", mimetype_list[$i]=".$mimetype_list[$i].
" mimefilename_list[$i]=".$mimefilename_list[$i].
" cid_list[$i]=".$cid_list[$i], LOG_DEBUG);
329 if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) {
330 $listofemailstoadd = explode(
',', $conf->global->MAIN_MAIL_AUTOCOPY_TO);
331 foreach ($listofemailstoadd as $key => $val) {
332 $emailtoadd = $listofemailstoadd[$key];
333 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
334 if (!empty($user) && !empty($user->email)) {
335 $emailtoadd = $user->email;
340 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
344 $listofemailstoadd[$key] = $emailtoadd;
346 unset($listofemailstoadd[$key]);
349 if (!empty($listofemailstoadd)) {
350 $addr_bcc .= ($addr_bcc ?
', ' :
'').join(
', ', $listofemailstoadd);
354 $this->subject = $subject;
360 $this->deliveryreceipt = $deliveryreceipt;
361 if (empty($replyto)) {
366 $this->trackid = $trackid;
368 $this->filename_list = $filename_list;
369 $this->mimetype_list = $mimetype_list;
370 $this->mimefilename_list = $mimefilename_list;
371 $this->cid_list = $cid_list;
373 if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) {
376 $this->addr_bcc =
'';
379 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
380 if (!empty($this->sendcontext)) {
381 $smtpContextKey = strtoupper($this->sendcontext);
383 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
384 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
388 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
392 if ($this->sendmode ==
'mail') {
403 if (!empty($moreinheader)) {
404 $smtp_headers .= $moreinheader;
410 if (!empty($this->html)) {
423 if (!empty($this->atleastonefile)) {
424 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
428 $this->headers = $smtp_headers.$mime_headers;
431 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
434 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
435 $this->message .= $text_body.$files_encoded;
436 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
437 } elseif ($this->sendmode ==
'smtps') {
441 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
442 $smtps =
new SMTPs();
443 $smtps->setCharSet($conf->file->character_set_client);
446 $subjecttouse = $this->subject;
451 $smtps->setSubject($subjecttouse);
454 $smtps->setTrackId($this->trackid);
457 if (!empty($moreinheader)) {
458 $smtps->setMoreInHeader($moreinheader);
461 if (!empty($this->html)) {
471 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
473 if ($this->msgishtml) {
474 $smtps->setBodyContent($msg,
'html');
476 $smtps->setBodyContent($msg,
'plain');
479 if ($this->atleastoneimage) {
480 foreach ($this->images_encoded as $img) {
481 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
485 if (!empty($this->atleastonefile)) {
486 foreach ($filename_list as $i => $val) {
487 $content = file_get_contents($filename_list[$i]);
488 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]);
492 $smtps->setCC($this->addr_cc);
493 $smtps->setBCC($this->addr_bcc);
494 $smtps->setErrorsTo($this->errors_to);
495 $smtps->setDeliveryReceipt($this->deliveryreceipt);
496 if (!empty($conf->global->$keyforsslseflsigned)) {
497 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
500 $host = dol_getprefix(
'email');
501 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
503 $this->smtps = $smtps;
504 } elseif ($this->sendmode ==
'swiftmailer') {
506 $host = dol_getprefix(
'email');
508 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
511 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
513 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
517 $this->message =
new Swift_Message();
520 $headers = $this->message->getHeaders();
522 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
523 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
524 $headerID = $this->msgid;
525 $msgid = $headers->get(
'Message-ID');
526 $msgid->setId($headerID);
533 $this->message->setSubject($this->subject);
535 $this->errors[] = $e->getMessage();
540 if (!empty($this->addr_from)) {
542 if (!empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) {
544 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
545 $adressEmailFrom = array();
546 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
547 $adressEmailFrom = reset($adressEmailFrom);
548 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
549 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
557 $this->errors[] = $e->getMessage();
562 if (!empty($this->addr_to)) {
566 $this->errors[] = $e->getMessage();
570 if (!empty($this->reply_to)) {
574 $this->errors[] = $e->getMessage();
578 if (!empty($this->errors_to)) {
580 $headers->addTextHeader(
'Errors-To', $this->
getArrayAddress($this->errors_to));
582 $this->errors[] = $e->getMessage();
587 $this->message->setCharSet($conf->file->character_set_client);
589 $this->errors[] = $e->getMessage();
592 if (!empty($this->html)) {
601 if ($this->atleastoneimage) {
602 foreach ($this->images_encoded as $img) {
604 $attachment = Swift_Image::fromPath($img[
'fullpath']);
606 $imgcid = $this->message->embed($attachment);
608 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
612 if ($this->msgishtml) {
613 $this->message->setBody($msg,
'text/html');
615 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
617 $this->message->setBody($msg,
'text/plain');
619 $this->message->addPart(
dol_nl2br($msg),
'text/html');
622 if (!empty($this->atleastonefile)) {
623 foreach ($filename_list as $i => $val) {
625 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
626 if (!empty($mimefilename_list[$i])) {
627 $attachment->setFilename($mimefilename_list[$i]);
629 $this->message->attach($attachment);
633 if (!empty($this->addr_cc)) {
637 $this->errors[] = $e->getMessage();
640 if (!empty($this->addr_bcc)) {
644 $this->errors[] = $e->getMessage();
648 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
650 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
652 $this->errors[] = $e->getMessage();
658 $this->error =
'Bad value for sendmode';
669 global $conf, $db, $langs, $hookmanager;
671 $errorlevel = error_reporting();
676 if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
677 if (!is_object($hookmanager)) {
678 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
681 $hookmanager->initHooks(array(
'mail'));
683 $parameters = array();
685 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
687 $this->error =
"Error in hook maildao sendMail ".$reshook;
688 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
696 $sendingmode = $this->sendmode;
697 if ($this->sendcontext ==
'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode ==
'mail') {
699 $listofmethods = array();
700 $listofmethods[
'mail'] =
'PHP mail function';
702 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
706 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
707 $linktoadminemailend =
'</a>';
708 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
709 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
710 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
711 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
712 if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) {
713 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
714 $this->errors[] = $langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
717 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
722 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) {
723 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
725 $tmparray1 = explode(
',', $this->addr_to);
726 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
727 $this->error =
'Too much recipients in to:';
728 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
731 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) {
732 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
734 $tmparray2 = explode(
',', $this->addr_cc);
735 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
736 $this->error =
'Too much recipients in cc:';
737 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
740 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) {
741 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
743 $tmparray3 = explode(
',', $this->addr_bcc);
744 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
745 $this->error =
'Too much recipients in bcc:';
746 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
749 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) {
750 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
752 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
753 $this->error =
'Too much recipients in to:, cc:, bcc:';
754 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
758 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
759 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
760 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
761 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
762 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
763 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
764 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
765 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
766 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
767 if (!empty($this->sendcontext)) {
768 $smtpContextKey = strtoupper($this->sendcontext);
770 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
771 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
772 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
773 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
774 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
775 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
776 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
777 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
778 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
779 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
784 if ($this->sendmode ==
'mail') {
787 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
792 if (isset($_SERVER[
"WINDIR"])) {
793 if (empty($this->addr_from)) {
794 $this->addr_from =
'robot@example.com';
796 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
801 if (!empty($conf->global->$keyforsmtpserver)) {
802 ini_set(
'SMTP', $conf->global->$keyforsmtpserver);
804 if (!empty($conf->global->$keyforsmtpport)) {
805 ini_set(
'smtp_port', $conf->global->$keyforsmtpport);
809 if ($res && !$this->subject) {
810 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
811 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
815 if ($res && !$dest) {
816 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
817 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
822 $additionnalparam =
'';
823 if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) {
828 $additionnalparam .= ($additionnalparam ?
' ' :
'').(!empty($conf->global->MAIN_MAIL_ERRORS_TO) ?
'-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from !=
'' ?
'-f'.$this->getValidAddress($this->addr_from, 2) :
''));
830 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
831 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
834 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) {
835 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
839 if (preg_match(
'/^win/i', PHP_OS)) {
842 if (preg_match(
'/^mac/i', PHP_OS)) {
846 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
848 $this->message = stripslashes($this->message);
850 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
855 $subjecttouse = $this->subject;
860 if (!empty($additionnalparam)) {
861 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
863 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
867 $langs->load(
"errors");
868 $this->error =
"Failed to send mail with php mail";
870 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
872 $this->error .=
".<br>";
873 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
874 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
876 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
880 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
884 if (isset($_SERVER[
"WINDIR"])) {
885 @ini_restore(
'sendmail_from');
889 if (!empty($conf->global->$keyforsmtpserver)) {
892 if (!empty($conf->global->$keyforsmtpport)) {
893 ini_restore(
'smtp_port');
895 } elseif ($this->sendmode ==
'smtps') {
896 if (!is_object($this->smtps)) {
897 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
"<br>Constructor of object CMailFile was not initialized without errors.";
898 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
904 $this->smtps->setTransportType(0);
907 if (empty($conf->global->$keyforsmtpserver)) {
908 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
910 if (empty($conf->global->$keyforsmtpport)) {
911 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
915 $server = $conf->global->$keyforsmtpserver;
917 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
920 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
923 $server = ($secure ? $secure.
'://' :
'').$server;
925 $port = $conf->global->$keyforsmtpport;
927 $this->smtps->setHost($server);
928 $this->smtps->setPort($port);
932 if (!empty($conf->global->$keyforsmtpid)) {
933 $loginid = $conf->global->$keyforsmtpid;
934 $this->smtps->setID($loginid);
936 if (!empty($conf->global->$keyforsmtppw)) {
937 $loginpass = $conf->global->$keyforsmtppw;
938 $this->smtps->setPW($loginpass);
942 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
944 $keyforsupportedoauth2array = $conf->global->$keyforsmtpoauthservice;
945 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
946 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
948 $keyforprovider =
'';
950 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
951 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
953 if (isset($supportedoauth2array)) {
954 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
956 $OAUTH_SERVICENAME =
'Unknown';
959 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
961 $storage =
new DoliStorage($db, $conf, $keyforprovider);
963 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
966 if (is_object($tokenobj)) {
967 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
970 if (is_object($tokenobj) && $expire) {
971 $credentials =
new Credentials(
976 $serviceFactory = new \OAuth\ServiceFactory();
977 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
979 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
981 $refreshtoken = $tokenobj->getRefreshToken();
982 $tokenobj = $apiService->refreshAccessToken($tokenobj);
983 $tokenobj->setRefreshToken($refreshtoken);
984 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
987 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
988 if (is_object($tokenobj)) {
989 $this->smtps->setToken($tokenobj->getAccessToken());
991 $this->error =
"Token not found";
995 $this->error = $e->getMessage();
996 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1001 $from = $this->smtps->getFrom(
'org');
1002 if ($res && !$from) {
1003 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - Sender address '$from' invalid";
1004 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1007 $dest = $this->smtps->getTo();
1008 if ($res && !$dest) {
1009 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - Recipient address '$dest' invalid";
1010 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1015 dol_syslog(
"CMailFile::sendfile: sendMsg, HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport, LOG_DEBUG);
1017 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1018 $this->smtps->setDebug(
true);
1021 $result = $this->smtps->sendMsg();
1023 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1029 $smtperrorcode = $this->smtps->lastretval;
1030 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1032 if ($smtperrorcode ==
'421') {
1047 $result = $this->smtps->getErrors();
1048 if (empty($this->error) && empty($result)) {
1049 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1052 if (empty($this->error)) {
1053 $this->error = $result;
1055 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - ".$this->error, LOG_ERR);
1058 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1063 } elseif ($this->sendmode ==
'swiftmailer') {
1066 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1069 if (empty($conf->global->$keyforsmtpserver)) {
1070 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1072 if (empty($conf->global->$keyforsmtpport)) {
1073 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1077 $server = $conf->global->$keyforsmtpserver;
1079 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1082 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1086 $this->transport =
new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
1088 if (!empty($conf->global->$keyforsmtpid)) {
1089 $this->transport->setUsername($conf->global->$keyforsmtpid);
1091 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1092 $this->transport->setPassword($conf->global->$keyforsmtppw);
1095 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1098 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1099 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1101 $keyforprovider =
'';
1103 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1104 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1106 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1108 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1110 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1113 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1116 if (is_object($tokenobj)) {
1117 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1120 if (is_object($tokenobj) && $expire) {
1121 $credentials =
new Credentials(
1126 $serviceFactory = new \OAuth\ServiceFactory();
1127 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1129 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1131 $refreshtoken = $tokenobj->getRefreshToken();
1132 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1133 $tokenobj->setRefreshToken($refreshtoken);
1134 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1136 if (is_object($tokenobj)) {
1137 $this->transport->setAuthMode(
'XOAUTH2');
1138 $this->transport->setPassword($tokenobj->getAccessToken());
1140 $this->errors[] =
"Token not found";
1144 $this->errors[] = $e->getMessage();
1145 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1148 if (!empty($conf->global->$keyforsslseflsigned)) {
1149 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1154 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1155 $this->message->setEncoder($contentEncoderBase64);
1158 $this->mailer =
new Swift_Mailer($this->transport);
1161 if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) {
1162 $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
1163 $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
1164 $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
1165 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1166 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1169 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1171 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1174 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1177 dol_syslog(
"CMailFile::sendfile: mailer->send, HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport, LOG_DEBUG);
1180 $failedRecipients = array();
1182 $result = $this->mailer->send($this->message, $failedRecipients);
1184 $this->errors[] = $e->getMessage();
1186 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1191 if (!empty($this->error) || !empty($this->errors) || !$result) {
1192 if (!empty($failedRecipients)) {
1193 $this->errors[] =
'Transport failed for the following addresses: "' . join(
'", "', $failedRecipients) .
'".';
1195 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1198 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1202 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1208 return 'Bad value for sendmode';
1212 foreach ($this->html_images as $val) {
1213 if (!empty($val[
'type']) && $val[
'type'] ==
'cidfromdata') {
1218 $parameters = array(
'sent' => $res);
1220 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1222 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1223 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1228 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1229 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1232 error_reporting($errorlevel);
1245 return '=?'.$conf->file->character_set_client.
'?B?'.base64_encode($stringtoencode).
'?=';
1260 if (is_readable($newsourcefile)) {
1261 $contents = file_get_contents($newsourcefile);
1262 $encoded = chunk_split(base64_encode($contents), 76, $this->eol);
1265 $this->error =
"Error in _encode_file() method: Can't read file '".$sourcefile.
"'";
1266 dol_syslog(
"CMailFile::_encode_file: ".$this->error, LOG_ERR);
1283 global $conf, $dolibarr_main_data_root;
1285 if (@is_writeable($dolibarr_main_data_root)) {
1286 $outputfile = $dolibarr_main_data_root.
"/dolibarr_mail.log";
1287 $fp = fopen($outputfile,
"w");
1289 if ($this->sendmode ==
'mail') {
1290 fputs($fp, $this->headers);
1291 fputs($fp, $this->eol);
1292 fputs($fp, $this->message);
1293 } elseif ($this->sendmode ==
'smtps') {
1294 fputs($fp, $this->smtps->log);
1295 } elseif ($this->sendmode ==
'swiftmailer') {
1296 fputs($fp, $this->logger->dump());
1304 $destfile = $dolibarr_main_data_root.
"/dolibarr_mail.".
dol_print_date(
dol_now(),
'dayhourlog',
'gmt').
".log";
1306 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1307 dol_move($outputfile, $destfile, 0, 1, 0, 0);
1322 global $dolibarr_main_data_root;
1324 if (@is_writeable($dolibarr_main_data_root)) {
1325 $srcfile = $dolibarr_main_data_root.
"/dolibarr_mail.log";
1331 if (defined(
'SYSLOG_FILE_NO_ERROR')) {
1332 $filefd = @fopen($srcfile,
'a+');
1334 $filefd = fopen($srcfile,
'a+');
1337 fwrite($filefd, $message.
"\n");
1345 $destfile = $dolibarr_main_data_root.
"/dolibarr_mail.".
dol_print_date(
dol_now(),
'dayhourlog',
'gmt').
".err";
1347 $destfile = $dolibarr_main_data_root.
"/dolibarr_mail.err";
1350 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1351 dol_move($srcfile, $destfile, 0, 1, 0, 0);
1364 if (!preg_match(
'/^[\s\t]*<html/i', $msg)) {
1365 $out =
"<html><head><title></title>";
1366 if (!empty($this->styleCSS)) {
1369 $out .=
"</head><body";
1370 if (!empty($this->bodyCSS)) {
1375 $out .=
"</body></html>";
1390 if (!empty($this->css)) {
1392 $this->styleCSS =
'<style type="text/css">';
1393 $this->styleCSS .=
'body {';
1395 if ($this->css[
'bgcolor']) {
1396 $this->styleCSS .=
' background-color: '.$this->css[
'bgcolor'].
';';
1397 $this->bodyCSS .=
' bgcolor="'.$this->css[
'bgcolor'].
'"';
1399 if ($this->css[
'bgimage']) {
1401 $this->styleCSS .=
' background-image: url("cid:'.$this->css[
'bgimage_cid'].
'");';
1403 $this->styleCSS .=
'}';
1404 $this->styleCSS .=
'</style>';
1421 $host = dol_getprefix(
'email');
1425 $out .=
"From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
1426 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
1427 $out .=
"To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
1430 $out .=
"Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
1431 if (isset($this->reply_to) && $this->reply_to) {
1432 $out .=
"Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
1434 if (isset($this->errors_to) && $this->errors_to) {
1435 $out .=
"Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1439 if (isset($this->addr_cc) && $this->addr_cc) {
1440 $out .=
"Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1442 if (isset($this->addr_bcc) && $this->addr_bcc) {
1443 $out .=
"Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2;
1447 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1448 $out .=
"Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1453 $out .=
'Date: '.date(
"r").$this->eol2;
1455 $trackid = $this->trackid;
1458 $this->msgid = time().
'.phpmail-dolibarr-'.$trackid.
'@'.$host;
1459 $out .=
'Message-ID: <'.$this->msgid.
">".$this->eol2;
1461 $out .=
'X-Dolibarr-TRACKID: '.$trackid.
'@'.$host.$this->eol2;
1463 $this->msgid = time().
'.phpmail@'.$host;
1464 $out .=
'Message-ID: <'.$this->msgid.
">".$this->eol2;
1467 if (!empty($_SERVER[
'REMOTE_ADDR'])) {
1468 $out .=
"X-RemoteAddr: ".$_SERVER[
'REMOTE_ADDR'].$this->eol2;
1470 $out .=
"X-Mailer: Dolibarr version ".DOL_VERSION.
" (using php mail)".$this->eol2;
1471 $out .=
"Mime-Version: 1.0".$this->eol2;
1475 $out .=
"Content-Type: multipart/mixed;".$this->eol2.
" boundary=\"".$this->mixed_boundary.
"\"".$this->eol2;
1476 $out .=
"Content-Transfer-Encoding: 8bit".$this->eol2;
1478 dol_syslog(
"CMailFile::write_smtpheaders smtp_header=\n".$out);
1497 if (is_array($filename_list)) {
1498 $filename_list_size = count($filename_list);
1499 for ($i = 0; $i < $filename_list_size; $i++) {
1500 if ($filename_list[$i]) {
1501 if ($mimefilename_list[$i]) {
1502 $filename_list[$i] = $mimefilename_list[$i];
1504 $out .=
"X-attachments: $filename_list[$i]".$this->eol2;
1509 dol_syslog(
"CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1527 $out .=
"--".$this->mixed_boundary.$this->eol;
1529 if ($this->atleastoneimage) {
1530 $out .=
"Content-Type: multipart/alternative;".$this->eol.
" boundary=\"".$this->alternative_boundary.
"\"".$this->eol;
1532 $out .=
"--".$this->alternative_boundary.$this->eol;
1536 $strContent = preg_replace(
"/(?<!\r)\n/si",
"\r\n", $msgtext);
1537 if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
1538 $strContent = preg_replace(
"/\r\n/si",
"\n", $strContent);
1541 $strContentAltText =
'';
1542 if ($this->msgishtml) {
1544 $strContentAltText = preg_replace(
"/<br\s*[^>]*>/",
" ", $strContent);
1546 $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1547 $strContentAltText = trim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ?
"\r\n" :
"\n"));
1556 $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ?
"\r\n" :
"\n"));
1558 if ($this->msgishtml) {
1559 if ($this->atleastoneimage) {
1560 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1562 $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol;
1563 $out .=
"--".$this->alternative_boundary.$this->eol;
1564 $out .=
"Content-Type: multipart/related;".$this->eol.
" boundary=\"".$this->related_boundary.
"\"".$this->eol;
1566 $out .=
"--".$this->related_boundary.$this->eol;
1569 if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1570 $out .=
"Content-Type: multipart/alternative;".$this->eol.
" boundary=\"".$this->alternative_boundary.
"\"".$this->eol;
1572 $out .=
"--".$this->alternative_boundary.$this->eol;
1573 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1575 $out .= $this->eol.$strContentAltText.$this->eol;
1576 $out .=
"--".$this->alternative_boundary.$this->eol;
1579 $out .=
"Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1581 $out .= $this->eol.$strContent.$this->eol;
1583 if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1584 $out .=
"--".$this->alternative_boundary.
"--".$this->eol;
1587 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1589 $out .= $this->eol.$strContent.$this->eol;
1595 if ($this->atleastoneimage) {
1598 $out .=
"--".$this->related_boundary.
"--".$this->eol;
1599 $out .= $this->eol.
"--".$this->alternative_boundary.
"--".$this->eol;
1616 private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
1621 $filename_list_size = count($filename_list);
1622 for ($i = 0; $i < $filename_list_size; $i++) {
1623 if ($filename_list[$i]) {
1626 if ($encoded >= 0) {
1627 if ($mimefilename_list[$i]) {
1628 $filename_list[$i] = $mimefilename_list[$i];
1630 if (!$mimetype_list[$i]) {
1631 $mimetype_list[$i] =
"application/octet-stream";
1634 $out .=
"--".$this->mixed_boundary.$this->eol;
1635 $out .=
"Content-Disposition: attachment; filename=\"".$filename_list[$i].
"\"".$this->eol;
1636 $out .=
"Content-Type: ".$mimetype_list[$i].
"; name=\"".$filename_list[$i].
"\"".$this->eol;
1637 $out .=
"Content-Transfer-Encoding: base64".$this->eol;
1638 $out .=
"Content-Description: ".$filename_list[$i].$this->eol;
1639 if (!empty($cidlist) && is_array($cidlist) && $cidlist[$i]) {
1640 $out .=
"X-Attachment-Id: ".$cidlist[$i].$this->eol;
1641 $out .=
"Content-ID: <".$cidlist[$i].
'>'.$this->eol;
1669 if (is_array($images_list)) {
1670 foreach ($images_list as $img) {
1671 dol_syslog(
"CMailFile::write_images: ".$img[
"name"]);
1673 $out .=
"--".$this->related_boundary.$this->eol;
1674 $out .=
"Content-Type: ".$img[
"content_type"].
"; name=\"".$img[
"name"].
"\"".$this->eol;
1675 $out .=
"Content-Transfer-Encoding: base64".$this->eol;
1676 $out .=
"Content-Disposition: inline; filename=\"".$img[
"name"].
"\"".$this->eol;
1677 $out .=
"Content-ID: <".$img[
"cid"].
">".$this->eol;
1679 $out .= $img[
"image_encoded"];
1704 if (function_exists(
'fsockopen')) {
1705 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
1706 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
1707 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
1708 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
1709 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
1710 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
1711 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
1712 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
1713 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
1715 if (!empty($this->sendcontext)) {
1716 $smtpContextKey = strtoupper($this->sendcontext);
1718 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
1719 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
1720 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
1721 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
1722 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
1723 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
1724 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
1725 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
1726 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
1727 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
1732 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1733 $host =
'ssl://'.$host;
1738 dol_syslog(
"Try socket connection to host=".$host.
" port=".$port);
1740 $errno = 0; $errstr =
'';
1741 if ($socket = @fsockopen(
1749 if (function_exists(
'stream_set_timeout')) {
1750 stream_set_timeout($socket, $timeout, 0);
1760 $this->error =
utf8_check(
'Error '.$errno.
' - '.$errstr) ?
'Error '.$errno.
' - '.$errstr : utf8_encode(
'Error '.$errno.
' - '.$errstr);
1779 $server_response =
'';
1781 while (substr($server_response, 3, 1) !=
' ') {
1782 if (!($server_response = fgets($socket, 256))) {
1783 $this->error =
"Couldn't get mail server response codes";
1788 if (!(substr($server_response, 0, 3) == $response)) {
1789 $this->error =
"Ran into problems sending Mail.\r\nResponse: $server_response";
1805 $extensions = array_keys($this->image_types);
1811 preg_match_all(
'/(?:"|\')([^"\']+\.('.implode(
'|', $extensions).
'))(?:"|\')/Ui', $this->html, $matches);
1813 if (!empty($matches) && !empty($matches[1])) {
1816 foreach ($matches[1] as $full) {
1818 if (preg_match(
'/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) {
1821 if (file_exists($images_dir.
'/'.$img)) {
1823 $src = preg_quote($full,
'/');
1825 $this->html_images[$i][
"fullpath"] = $images_dir.
'/'.$img;
1827 $this->html_images[$i][
"name"] = $img;
1830 if (preg_match(
'/^.+\.(\w{3,4})$/', $img, $regext)) {
1831 $ext = strtolower($regext[1]);
1832 $this->html_images[$i][
"content_type"] = $this->image_types[$ext];
1835 $this->html_images[$i][
"cid"] =
dol_hash($this->html_images[$i][
"fullpath"],
'md5');
1837 $this->html_images[$i][
"type"] =
'cidfromurl';
1839 $this->html = preg_replace(
"/src=\"$src\"|src='$src'/i",
"src=\"cid:".$this->html_images[$i][
"cid"].
"\"", $this->html);
1845 if (!empty($this->html_images)) {
1850 foreach ($this->html_images as $img) {
1851 $fullpath = $images_dir.
'/'.$img[
"name"];
1854 if (!in_array($fullpath, $inline)) {
1856 if ($image = file_get_contents($fullpath)) {
1859 preg_match(
'/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img[
"name"], $regs);
1860 $imgName = $regs[1];
1862 $this->images_encoded[$i][
'name'] = $imgName;
1863 $this->images_encoded[$i][
'fullpath'] = $fullpath;
1864 $this->images_encoded[$i][
'content_type'] = $img[
"content_type"];
1865 $this->images_encoded[$i][
'cid'] = $img[
"cid"];
1867 $this->images_encoded[$i][
"image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1868 $inline[] = $fullpath;
1895 $extensions = array_keys($this->image_types);
1897 if ($images_dir && !
dol_is_dir($images_dir)) {
1914 preg_match_all(
'/src="data:image\/('.implode(
'|', $extensions).
');base64,([^"]+)"/Ui', $this->html, $matches);
1916 if (!empty($matches) && !empty($matches[1])) {
1917 if (empty($images_dir)) {
1919 $this->error =
'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk';
1923 $i = count($this->html_images);
1924 foreach ($matches[1] as $key => $ext) {
1926 $filecontent = $matches[2][$key];
1928 $cid =
'cid000'.dol_hash($filecontent,
'md5');
1930 $destfiletmp = $images_dir.
'/'.$cid.
'.'.$ext;
1933 dol_syslog(
"write the cid file ".$destfiletmp);
1934 $fhandle = @fopen($destfiletmp,
'w');
1936 $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent));
1940 $this->errors[] =
"Failed to open file '".$destfiletmp.
"' for write";
1945 if (file_exists($destfiletmp)) {
1947 $this->html_images[$i][
"fullpath"] = $destfiletmp;
1949 $this->html_images[$i][
"name"] = basename($destfiletmp);
1951 $this->html_images[$i][
"content_type"] = $this->image_types[strtolower($ext)];
1953 $this->html_images[$i][
"cid"] = $cid;
1955 $this->html_images[$i][
"type"] =
'cidfromdata';
1957 $this->html = str_replace(
'src="data:image/'.$ext.
';base64,'.$filecontent.
'"',
'src="cid:'.$this->html_images[$i][
"cid"].
'"', $this->html);
1983 public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
1989 $arrayaddress = explode(
',', $address);
1993 foreach ($arrayaddress as $val) {
1995 if (preg_match(
'/^(.*)<(.*)>$/i', trim($val), $regs)) {
1996 $name = trim($regs[1]);
1997 $email = trim($regs[2]);
2000 $email = trim($val);
2008 $newemail = $name ? $name : $email;
2009 $newemail =
'<a href="mailto:'.$email.
'">'.$newemail.
'</a>';
2012 $newemail = $name ? $name : $email;
2017 if ($format == 1 || $format == 3) {
2018 $newemail =
'<'.$email.
'>';
2020 if ($format == 0 || $format == 3) {
2021 if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) {
2022 $newemail =
'<'.$email.
'>';
2024 $newemail =
'<'.$email.
'>';
2026 $newemail = ($format == 3 ?
'"' :
'').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ?
'"' :
'').
' <'.$email.
'>';
2030 $ret = ($ret ? $ret.
',' :
'').$newemail;
2033 if ($maxnumberofemail && $i >= $maxnumberofemail) {
2034 if (count($arrayaddress) > $maxnumberofemail) {
2058 $arrayaddress = explode(
',', $address);
2061 foreach ($arrayaddress as $val) {
2062 if (preg_match(
'/^(.*)<(.*)>$/i', trim($val), $regs)) {
2063 $name = trim($regs[1]);
2064 $email = trim($regs[2]);
2067 $email = trim($val);
2070 $ret[$email] = empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL) ? $name :
null;
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
_encode_file($sourcefile)
Read a file on disk and return encoded content for emails (mode = 'mail')
write_body($msgtext)
Return email content (mode = 'mail')
$bodyCSS
Defined background directly in body tag.
dump_mail()
Write content of a SMTP request into a dump file (mode = all) Used for debugging.
sendfile()
Send mail that was prepared by constructor.
save_dump_mail_in_err($message='')
Save content if mail is in error Used for debugging.
static encodetorfc2822($stringtoencode)
Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word.
checkIfHTML($msg)
Correct an uncomplete html string.
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
write_images($images_list)
Attach an image to email (mode = 'mail')
server_parse($socket, $response)
This function has been modified as provided by SirSir to allow multiline responses when using SMTP Ex...
__construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='', $upload_dir_tmp='')
CMailFile.
write_smtpheaders()
Create SMTP headers (mode = 'mail')
findHtmlImagesIsSrcData($images_dir)
Seearch images with data:image format into html message.
$styleCSS
Defined css style for body background.
write_mimeheaders($filename_list, $mimefilename_list)
Create header MIME (mode = 'mail')
check_server_port($host, $port)
Try to create a socket connection.
buildCSS()
Build a css style (mode = all) into this->styleCSS and this->bodyCSS.
write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
Attach file to email (mode = 'mail')
static getArrayAddress($address)
Return a formatted array of address string for SMTP protocol.
findHtmlImages($images_dir)
Search images into html message and init array this->images_encoded if found.
Class to construct and send SMTP compliant email, even to a secure SMTP server, regardless of platfor...
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
ascii_check($str)
Check if a string is in ASCII.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
utf8_check($str)
Check if a string is in UTF8.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_sanitizeEmail($stringtoclean)
Clean a string to use it as an Email.
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.