33 use OAuth\Common\Storage\DoliStorage;
34 use OAuth\Common\Consumer\Credentials;
61 public $mixed_boundary;
62 public $related_boundary;
63 public $alternative_boundary;
64 public $deliveryreceipt;
66 public $atleastonefile;
79 public $errors = array();
114 public $filename_list = array();
118 public $mimetype_list = array();
122 public $mimefilename_list = array();
126 public $cid_list = array();
130 public $image_boundary;
131 public $atleastoneimage = 0;
132 public $html_images = array();
133 public $images_encoded = array();
134 public $image_types = array(
135 'gif' =>
'image/gif',
136 'jpg' =>
'image/jpeg',
137 'jpeg' =>
'image/jpeg',
138 'jpe' =>
'image/jpeg',
139 'bmp' =>
'image/bmp',
140 'png' =>
'image/png',
141 'tif' =>
'image/tiff',
142 'tiff' =>
'image/tiff',
168 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 =
'')
170 global $conf, $dolibarr_main_data_root, $user;
173 if (is_array($mimefilename_list)) {
174 foreach ($mimefilename_list as $key => $val) {
181 $this->sendcontext = $sendcontext;
184 $this->sendmode =
'';
185 if (!empty($this->sendcontext)) {
186 $smtpContextKey = strtoupper($this->sendcontext);
188 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
189 $this->sendmode = $smtpContextSendMode;
192 if (empty($this->sendmode)) {
193 $this->sendmode = (!empty($conf->global->MAIN_MAIL_SENDMODE) ? $conf->global->MAIN_MAIL_SENDMODE :
'mail');
199 $this->eol2 =
"\r\n";
200 if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
203 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
207 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
210 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"), 3);
213 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"), 3);
215 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" 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 upload_dir_tmp=$upload_dir_tmp", LOG_DEBUG);
216 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
218 if (empty($subject)) {
219 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
220 $this->error =
'ErrorSubjectIsRequired';
224 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
229 if ($msgishtml == -1) {
230 $this->msgishtml = 0;
232 $this->msgishtml = 1;
235 $this->msgishtml = $msgishtml;
238 global $dolibarr_main_url_root;
241 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
242 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
246 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
248 if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) {
249 $this->msgishtml = 1;
253 if ($this->msgishtml) {
257 if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) {
261 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
263 if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA)) {
271 foreach ($this->html_images as $i => $val) {
272 if ($this->html_images[$i]) {
273 $this->atleastoneimage = 1;
274 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
275 $posindice = count($filename_list);
276 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
277 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
278 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
279 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
281 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
288 if (is_array($filename_list)) {
289 foreach ($filename_list as $i => $val) {
290 if ($filename_list[$i]) {
291 $this->atleastonefile = 1;
292 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);
299 if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) {
300 $listofemailstoadd = explode(
',', $conf->global->MAIN_MAIL_AUTOCOPY_TO);
301 foreach ($listofemailstoadd as $key => $val) {
302 $emailtoadd = $listofemailstoadd[$key];
303 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
304 if (!empty($user) && !empty($user->email)) {
305 $emailtoadd = $user->email;
310 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
314 $listofemailstoadd[$key] = $emailtoadd;
316 unset($listofemailstoadd[$key]);
319 if (!empty($listofemailstoadd)) {
320 $addr_bcc .= ($addr_bcc ?
', ' :
'').join(
', ', $listofemailstoadd);
324 $this->subject = $subject;
330 $this->deliveryreceipt = $deliveryreceipt;
331 if (empty($replyto)) {
336 $this->trackid = $trackid;
338 $this->filename_list = $filename_list;
339 $this->mimetype_list = $mimetype_list;
340 $this->mimefilename_list = $mimefilename_list;
341 $this->cid_list = $cid_list;
343 if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) {
346 $this->addr_bcc =
'';
349 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
350 if (!empty($this->sendcontext)) {
351 $smtpContextKey = strtoupper($this->sendcontext);
353 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
354 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
360 if ($this->sendmode ==
'mail') {
371 if (!empty($moreinheader)) {
372 $smtp_headers .= $moreinheader;
378 if (!empty($this->html)) {
391 if (!empty($this->atleastonefile)) {
392 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
396 $this->headers = $smtp_headers.$mime_headers;
399 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
402 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
403 $this->message .= $text_body.$files_encoded;
404 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
405 } elseif ($this->sendmode ==
'smtps') {
409 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
410 $smtps =
new SMTPs();
411 $smtps->setCharSet($conf->file->character_set_client);
414 $subjecttouse = $this->subject;
419 $smtps->setSubject($subjecttouse);
422 $smtps->setTrackId($this->trackid);
425 if (!empty($moreinheader)) {
426 $smtps->setMoreInHeader($moreinheader);
429 if (!empty($this->html)) {
439 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
441 if ($this->msgishtml) {
442 $smtps->setBodyContent($msg,
'html');
444 $smtps->setBodyContent($msg,
'plain');
447 if ($this->atleastoneimage) {
448 foreach ($this->images_encoded as $img) {
449 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
453 if (!empty($this->atleastonefile)) {
454 foreach ($filename_list as $i => $val) {
455 $content = file_get_contents($filename_list[$i]);
456 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]);
460 $smtps->setCC($this->addr_cc);
461 $smtps->setBCC($this->addr_bcc);
462 $smtps->setErrorsTo($this->errors_to);
463 $smtps->setDeliveryReceipt($this->deliveryreceipt);
464 if (!empty($conf->global->$keyforsslseflsigned)) {
465 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
468 $host = dol_getprefix(
'email');
469 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
471 $this->smtps = $smtps;
472 } elseif ($this->sendmode ==
'swiftmailer') {
474 $host = dol_getprefix(
'email');
476 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
479 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
481 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
485 $this->message =
new Swift_Message();
488 $headers = $this->message->getHeaders();
489 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
490 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
491 $headerID = $this->msgid;
492 $msgid = $headers->get(
'Message-ID');
493 $msgid->setId($headerID);
494 $headers->addIdHeader(
'References', $headerID);
499 $result = $this->message->setSubject($this->subject);
501 $this->errors[] = $e->getMessage();
506 if (!empty($this->addr_from)) {
508 if (!empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) {
510 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
511 $adressEmailFrom = array();
512 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
513 $adressEmailFrom = reset($adressEmailFrom);
514 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
515 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
523 $this->errors[] = $e->getMessage();
528 if (!empty($this->addr_to)) {
532 $this->errors[] = $e->getMessage();
536 if (!empty($this->reply_to)) {
540 $this->errors[] = $e->getMessage();
545 $this->message->setCharSet($conf->file->character_set_client);
547 $this->errors[] = $e->getMessage();
550 if (!empty($this->html)) {
559 if ($this->atleastoneimage) {
560 foreach ($this->images_encoded as $img) {
562 $attachment = Swift_Image::fromPath($img[
'fullpath']);
564 $imgcid = $this->message->embed($attachment);
566 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
570 if ($this->msgishtml) {
571 $this->message->setBody($msg,
'text/html');
573 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
575 $this->message->setBody($msg,
'text/plain');
577 $this->message->addPart(
dol_nl2br($msg),
'text/html');
580 if (!empty($this->atleastonefile)) {
581 foreach ($filename_list as $i => $val) {
583 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
584 if (!empty($mimefilename_list[$i])) {
585 $attachment->setFilename($mimefilename_list[$i]);
587 $this->message->attach($attachment);
591 if (!empty($this->addr_cc)) {
595 $this->errors[] = $e->getMessage();
598 if (!empty($this->addr_bcc)) {
602 $this->errors[] = $e->getMessage();
606 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
608 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
610 $this->errors[] = $e->getMessage();
616 $this->error =
'Bad value for sendmode';
628 global $conf, $db, $langs;
630 $errorlevel = error_reporting();
635 if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
636 require_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
638 $hookmanager->initHooks(array(
'mail'));
640 $parameters = array();
642 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
644 $this->error =
"Error in hook maildao sendMail ".$reshook;
645 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
653 $sendingmode = $this->sendmode;
654 if ($this->sendcontext ==
'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode ==
'mail') {
656 $listofmethods = array();
657 $listofmethods[
'mail'] =
'PHP mail function';
659 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
663 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
664 $linktoadminemailend =
'</a>';
665 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
666 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
667 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
668 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
669 if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) {
670 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
671 $this->errors[] = $langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
677 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) {
678 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
680 $tmparray1 = explode(
',', $this->addr_to);
681 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
682 $this->error =
'Too much recipients in to:';
683 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
686 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) {
687 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
689 $tmparray2 = explode(
',', $this->addr_cc);
690 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
691 $this->error =
'Too much recipients in cc:';
692 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
695 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) {
696 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
698 $tmparray3 = explode(
',', $this->addr_bcc);
699 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
700 $this->error =
'Too much recipients in bcc:';
701 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
704 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) {
705 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
707 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
708 $this->error =
'Too much recipients in to:, cc:, bcc:';
709 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
713 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
714 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
715 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
716 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
717 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
718 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
719 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
720 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
721 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
722 if (!empty($this->sendcontext)) {
723 $smtpContextKey = strtoupper($this->sendcontext);
725 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
726 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
727 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
728 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
729 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
730 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
731 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
732 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
733 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
734 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
739 if ($this->sendmode ==
'mail') {
742 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
743 dol_syslog(
"CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
747 if (isset($_SERVER[
"WINDIR"])) {
748 if (empty($this->addr_from)) {
749 $this->addr_from =
'robot@example.com';
751 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
756 if (!empty($conf->global->$keyforsmtpserver)) {
757 ini_set(
'SMTP', $conf->global->$keyforsmtpserver);
759 if (!empty($conf->global->$keyforsmtpport)) {
760 ini_set(
'smtp_port', $conf->global->$keyforsmtpport);
764 if ($res && !$this->subject) {
765 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
766 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
770 if ($res && !$dest) {
771 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
772 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
777 $additionnalparam =
'';
778 if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) {
783 $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) :
''));
785 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
786 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
789 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) {
790 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
794 if (preg_match(
'/^win/i', PHP_OS)) {
797 if (preg_match(
'/^mac/i', PHP_OS)) {
801 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
803 $this->message = stripslashes($this->message);
805 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
810 $subjecttouse = $this->subject;
815 if (!empty($additionnalparam)) {
816 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
818 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
822 $langs->load(
"errors");
823 $this->error =
"Failed to send mail with php mail";
825 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
827 $this->error .=
".<br>";
828 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
829 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
831 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
835 if (isset($_SERVER[
"WINDIR"])) {
836 @ini_restore(
'sendmail_from');
840 if (!empty($conf->global->$keyforsmtpserver)) {
843 if (!empty($conf->global->$keyforsmtpport)) {
844 ini_restore(
'smtp_port');
846 } elseif ($this->sendmode ==
'smtps') {
847 if (!is_object($this->smtps)) {
848 $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.";
849 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
855 $this->smtps->setTransportType(0);
858 if (empty($conf->global->$keyforsmtpserver)) {
859 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
861 if (empty($conf->global->$keyforsmtpport)) {
862 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
866 $server = $conf->global->$keyforsmtpserver;
868 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
871 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
874 $server = ($secure ? $secure.
'://' :
'').$server;
876 $port = $conf->global->$keyforsmtpport;
878 $this->smtps->setHost($server);
879 $this->smtps->setPort($port);
883 if (!empty($conf->global->$keyforsmtpid)) {
884 $loginid = $conf->global->$keyforsmtpid;
885 $this->smtps->setID($loginid);
887 if (!empty($conf->global->$keyforsmtppw)) {
888 $loginpass = $conf->global->$keyforsmtppw;
889 $this->smtps->setPW($loginpass);
893 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
894 $keyforsupportedoauth2array = $conf->global->$keyforsmtpoauthservice;
895 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
896 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
898 $keyforprovider =
'';
900 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
901 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
903 if (isset($supportedoauth2array)) {
904 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
906 $OAUTH_SERVICENAME =
'Unknown';
909 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
911 $storage =
new DoliStorage($db, $conf);
913 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
916 if (is_object($tokenobj)) {
917 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
920 if (is_object($tokenobj) && $expire) {
921 $credentials =
new Credentials(
926 $serviceFactory = new \OAuth\ServiceFactory();
927 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
929 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
931 $refreshtoken = $tokenobj->getRefreshToken();
932 $tokenobj = $apiService->refreshAccessToken($tokenobj);
933 $tokenobj->setRefreshToken($refreshtoken);
934 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
937 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
938 if (is_object($tokenobj)) {
939 $this->smtps->setToken($tokenobj->getAccessToken());
941 $this->error =
"Token not found";
945 $this->error = $e->getMessage();
946 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
951 $from = $this->smtps->getFrom(
'org');
952 if ($res && !$from) {
953 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - Sender address '$from' invalid";
954 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
957 $dest = $this->smtps->getTo();
958 if ($res && !$dest) {
959 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - Recipient address '$dest' invalid";
960 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
965 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
966 $this->smtps->setDebug(
true);
969 $result = $this->smtps->sendMsg();
971 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
975 $result = $this->smtps->getErrors();
976 if (empty($this->error) && empty($result)) {
977 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
980 if (empty($this->error)) {
981 $this->error = $result;
983 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - ".$this->error, LOG_ERR);
987 } elseif ($this->sendmode ==
'swiftmailer') {
990 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
993 if (empty($conf->global->$keyforsmtpserver)) {
994 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
996 if (empty($conf->global->$keyforsmtpport)) {
997 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1001 $server = $conf->global->$keyforsmtpserver;
1003 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1006 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1010 $this->transport =
new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
1012 if (!empty($conf->global->$keyforsmtpid)) {
1013 $this->transport->setUsername($conf->global->$keyforsmtpid);
1015 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1016 $this->transport->setPassword($conf->global->$keyforsmtppw);
1019 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1021 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1022 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1024 $keyforprovider =
'';
1026 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1027 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1029 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1031 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1033 $storage =
new DoliStorage($db, $conf);
1036 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1039 if (is_object($tokenobj)) {
1040 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1043 if (is_object($tokenobj) && $expire) {
1044 $credentials =
new Credentials(
1049 $serviceFactory = new \OAuth\ServiceFactory();
1050 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1052 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1054 $refreshtoken = $tokenobj->getRefreshToken();
1055 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1056 $tokenobj->setRefreshToken($refreshtoken);
1057 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1059 if (is_object($tokenobj)) {
1060 $this->transport->setAuthMode(
'XOAUTH2');
1061 $this->transport->setPassword($tokenobj->getAccessToken());
1063 $this->errors[] =
"Token not found";
1067 $this->errors[] = $e->getMessage();
1068 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1071 if (!empty($conf->global->$keyforsslseflsigned)) {
1072 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1077 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1078 $this->message->setEncoder($contentEncoderBase64);
1081 $this->mailer =
new Swift_Mailer($this->transport);
1084 if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) {
1085 $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
1086 $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
1087 $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
1088 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1089 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1092 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1094 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1097 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1101 $result = $this->mailer->send($this->message, $failedRecipients);
1103 $this->errors[] = $e->getMessage();
1105 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1110 if (!empty($this->error) || !empty($this->errors) || !$result) {
1111 if (!empty($failedRecipients)) {
1112 $this->errors[] =
'Transport failed for the following addresses: "' . join(
'", "', $failedRecipients) .
'".';
1114 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1117 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1123 return 'Bad value for sendmode';
1126 $parameters = array(
'sent' => $res);
1128 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1130 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1131 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1136 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1137 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1140 error_reporting($errorlevel);
1154 return '=?'.$conf->file->character_set_client.
'?B?'.base64_encode($stringtoencode).
'?=';
1169 if (is_readable($newsourcefile)) {
1170 $contents = file_get_contents($newsourcefile);
1171 $encoded = chunk_split(base64_encode($contents), 76, $this->eol);
1174 $this->error =
"Error: Can't read file '".$sourcefile.
"' into _encode_file";
1175 dol_syslog(
"CMailFile::encode_file: ".$this->error, LOG_ERR);
1192 global $conf, $dolibarr_main_data_root;
1194 if (@is_writeable($dolibarr_main_data_root)) {
1195 $outputfile = $dolibarr_main_data_root.
"/dolibarr_mail.log";
1196 $fp = fopen($outputfile,
"w");
1198 if ($this->sendmode ==
'mail') {
1199 fputs($fp, $this->headers);
1200 fputs($fp, $this->eol);
1201 fputs($fp, $this->message);
1202 } elseif ($this->sendmode ==
'smtps') {
1203 fputs($fp, $this->smtps->log);
1204 } elseif ($this->sendmode ==
'swiftmailer') {
1205 fputs($fp, $this->logger->dump());
1209 if (!empty($conf->global->MAIN_UMASK)) {
1210 @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
1224 if (!preg_match(
'/^[\s\t]*<html/i', $msg)) {
1225 $out =
"<html><head><title></title>";
1226 if (!empty($this->styleCSS)) {
1229 $out .=
"</head><body";
1230 if (!empty($this->bodyCSS)) {
1235 $out .=
"</body></html>";
1250 if (!empty($this->css)) {
1252 $this->styleCSS =
'<style type="text/css">';
1253 $this->styleCSS .=
'body {';
1255 if ($this->css[
'bgcolor']) {
1256 $this->styleCSS .=
' background-color: '.$this->css[
'bgcolor'].
';';
1257 $this->bodyCSS .=
' bgcolor="'.$this->css[
'bgcolor'].
'"';
1259 if ($this->css[
'bgimage']) {
1261 $this->styleCSS .=
' background-image: url("cid:'.$this->css[
'bgimage_cid'].
'");';
1263 $this->styleCSS .=
'}';
1264 $this->styleCSS .=
'</style>';
1281 $host = dol_getprefix(
'email');
1285 $out .=
"From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
1286 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
1287 $out .=
"To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
1290 $out .=
"Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
1291 if (isset($this->reply_to) && $this->reply_to) {
1292 $out .=
"Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
1294 if (isset($this->errors_to) && $this->errors_to) {
1295 $out .=
"Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1299 if (isset($this->addr_cc) && $this->addr_cc) {
1300 $out .=
"Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1302 if (isset($this->addr_bcc) && $this->addr_bcc) {
1303 $out .=
"Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2;
1307 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1308 $out .=
"Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1313 $out .=
'Date: '.date(
"r").$this->eol2;
1315 $trackid = $this->trackid;
1318 $this->msgid = time().
'.phpmail-dolibarr-'.$trackid.
'@'.$host;
1319 $out .=
'Message-ID: <'.$this->msgid.
">".$this->eol2;
1320 $out .=
'References: <'.$this->msgid.
">".$this->eol2;
1321 $out .=
'X-Dolibarr-TRACKID: '.$trackid.
'@'.$host.$this->eol2;
1323 $this->msgid = time().
'.phpmail@'.$host;
1324 $out .=
'Message-ID: <'.$this->msgid.
">".$this->eol2;
1327 if (!empty($_SERVER[
'REMOTE_ADDR'])) {
1328 $out .=
"X-RemoteAddr: ".$_SERVER[
'REMOTE_ADDR'].$this->eol2;
1330 $out .=
"X-Mailer: Dolibarr version ".DOL_VERSION.
" (using php mail)".$this->eol2;
1331 $out .=
"Mime-Version: 1.0".$this->eol2;
1335 $out .=
"Content-Type: multipart/mixed;".$this->eol2.
" boundary=\"".$this->mixed_boundary.
"\"".$this->eol2;
1336 $out .=
"Content-Transfer-Encoding: 8bit".$this->eol2;
1338 dol_syslog(
"CMailFile::write_smtpheaders smtp_header=\n".$out);
1357 if (is_array($filename_list)) {
1358 $filename_list_size = count($filename_list);
1359 for ($i = 0; $i < $filename_list_size; $i++) {
1360 if ($filename_list[$i]) {
1361 if ($mimefilename_list[$i]) {
1362 $filename_list[$i] = $mimefilename_list[$i];
1364 $out .=
"X-attachments: $filename_list[$i]".$this->eol2;
1369 dol_syslog(
"CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1387 $out .=
"--".$this->mixed_boundary.$this->eol;
1389 if ($this->atleastoneimage) {
1390 $out .=
"Content-Type: multipart/alternative;".$this->eol.
" boundary=\"".$this->alternative_boundary.
"\"".$this->eol;
1392 $out .=
"--".$this->alternative_boundary.$this->eol;
1396 $strContent = preg_replace(
"/(?<!\r)\n/si",
"\r\n", $msgtext);
1397 if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
1398 $strContent = preg_replace(
"/\r\n/si",
"\n", $strContent);
1401 $strContentAltText =
'';
1402 if ($this->msgishtml) {
1404 $strContentAltText = preg_replace(
"/<br\s*[^>]*>/",
" ", $strContent);
1406 $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1407 $strContentAltText = trim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ?
"\r\n" :
"\n"));
1416 $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ?
"\r\n" :
"\n"));
1418 if ($this->msgishtml) {
1419 if ($this->atleastoneimage) {
1420 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1422 $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol;
1423 $out .=
"--".$this->alternative_boundary.$this->eol;
1424 $out .=
"Content-Type: multipart/related;".$this->eol.
" boundary=\"".$this->related_boundary.
"\"".$this->eol;
1426 $out .=
"--".$this->related_boundary.$this->eol;
1429 if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1430 $out .=
"Content-Type: multipart/alternative;".$this->eol.
" boundary=\"".$this->alternative_boundary.
"\"".$this->eol;
1432 $out .=
"--".$this->alternative_boundary.$this->eol;
1433 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1435 $out .= $this->eol.$strContentAltText.$this->eol;
1436 $out .=
"--".$this->alternative_boundary.$this->eol;
1439 $out .=
"Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1441 $out .= $this->eol.$strContent.$this->eol;
1443 if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1444 $out .=
"--".$this->alternative_boundary.
"--".$this->eol;
1447 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1449 $out .= $this->eol.$strContent.$this->eol;
1455 if ($this->atleastoneimage) {
1458 $out .=
"--".$this->related_boundary.
"--".$this->eol;
1459 $out .= $this->eol.
"--".$this->alternative_boundary.
"--".$this->eol;
1476 private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
1481 $filename_list_size = count($filename_list);
1482 for ($i = 0; $i < $filename_list_size; $i++) {
1483 if ($filename_list[$i]) {
1486 if ($encoded >= 0) {
1487 if ($mimefilename_list[$i]) {
1488 $filename_list[$i] = $mimefilename_list[$i];
1490 if (!$mimetype_list[$i]) {
1491 $mimetype_list[$i] =
"application/octet-stream";
1494 $out .=
"--".$this->mixed_boundary.$this->eol;
1495 $out .=
"Content-Disposition: attachment; filename=\"".$filename_list[$i].
"\"".$this->eol;
1496 $out .=
"Content-Type: ".$mimetype_list[$i].
"; name=\"".$filename_list[$i].
"\"".$this->eol;
1497 $out .=
"Content-Transfer-Encoding: base64".$this->eol;
1498 $out .=
"Content-Description: ".$filename_list[$i].$this->eol;
1499 if (!empty($cidlist) && is_array($cidlist) && $cidlist[$i]) {
1500 $out .=
"X-Attachment-Id: ".$cidlist[$i].$this->eol;
1501 $out .=
"Content-ID: <".$cidlist[$i].
'>'.$this->eol;
1529 if (is_array($images_list)) {
1530 foreach ($images_list as $img) {
1531 dol_syslog(
"CMailFile::write_images: ".$img[
"name"]);
1533 $out .=
"--".$this->related_boundary.$this->eol;
1534 $out .=
"Content-Type: ".$img[
"content_type"].
"; name=\"".$img[
"name"].
"\"".$this->eol;
1535 $out .=
"Content-Transfer-Encoding: base64".$this->eol;
1536 $out .=
"Content-Disposition: inline; filename=\"".$img[
"name"].
"\"".$this->eol;
1537 $out .=
"Content-ID: <".$img[
"cid"].
">".$this->eol;
1539 $out .= $img[
"image_encoded"];
1564 if (function_exists(
'fsockopen')) {
1565 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
1566 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
1567 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
1568 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
1569 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
1570 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
1571 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
1572 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
1573 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
1575 if (!empty($this->sendcontext)) {
1576 $smtpContextKey = strtoupper($this->sendcontext);
1578 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
1579 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
1580 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
1581 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
1582 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
1583 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
1584 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
1585 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
1586 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
1587 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
1592 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1593 $host =
'ssl://'.$host;
1598 dol_syslog(
"Try socket connection to host=".$host.
" port=".$port);
1600 $errno = 0; $errstr =
'';
1601 if ($socket = @fsockopen(
1609 if (function_exists(
'stream_set_timeout')) {
1610 stream_set_timeout($socket, $timeout, 0);
1620 $this->error =
utf8_check(
'Error '.$errno.
' - '.$errstr) ?
'Error '.$errno.
' - '.$errstr : utf8_encode(
'Error '.$errno.
' - '.$errstr);
1639 $server_response =
'';
1641 while (substr($server_response, 3, 1) !=
' ') {
1642 if (!($server_response = fgets($socket, 256))) {
1643 $this->error =
"Couldn't get mail server response codes";
1648 if (!(substr($server_response, 0, 3) == $response)) {
1649 $this->error =
"Ran into problems sending Mail.\r\nResponse: $server_response";
1665 $extensions = array_keys($this->image_types);
1671 preg_match_all(
'/(?:"|\')([^"\']+\.('.implode(
'|', $extensions).
'))(?:"|\')/Ui', $this->html, $matches);
1673 if (!empty($matches)) {
1676 foreach ($matches[1] as $full) {
1678 if (preg_match(
'/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) {
1681 if (file_exists($images_dir.
'/'.$img)) {
1683 $src = preg_quote($full,
'/');
1685 $this->html_images[$i][
"fullpath"] = $images_dir.
'/'.$img;
1687 $this->html_images[$i][
"name"] = $img;
1690 if (preg_match(
'/^.+\.(\w{3,4})$/', $img, $regext)) {
1691 $ext = strtolower($regext[1]);
1692 $this->html_images[$i][
"content_type"] = $this->image_types[$ext];
1695 $this->html_images[$i][
"cid"] =
dol_hash(uniqid(time()), 3);
1697 $this->html_images[$i][
"type"] =
'cidfromurl';
1699 $this->html = preg_replace(
"/src=\"$src\"|src='$src'/i",
"src=\"cid:".$this->html_images[$i][
"cid"].
"\"", $this->html);
1705 if (!empty($this->html_images)) {
1710 foreach ($this->html_images as $img) {
1711 $fullpath = $images_dir.
'/'.$img[
"name"];
1714 if (!in_array($fullpath, $inline)) {
1716 if ($image = file_get_contents($fullpath)) {
1719 preg_match(
'/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img[
"name"], $regs);
1720 $imgName = $regs[1];
1722 $this->images_encoded[$i][
'name'] = $imgName;
1723 $this->images_encoded[$i][
'fullpath'] = $fullpath;
1724 $this->images_encoded[$i][
'content_type'] = $img[
"content_type"];
1725 $this->images_encoded[$i][
'cid'] = $img[
"cid"];
1727 $this->images_encoded[$i][
"image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1728 $inline[] = $fullpath;
1754 $extensions = array_keys($this->image_types);
1756 if ($images_dir && !
dol_is_dir($images_dir)) {
1773 preg_match_all(
'/src="data:image\/('.implode(
'|', $extensions).
');base64,([^"]+)"/Ui', $this->html, $matches);
1775 if (!empty($matches) && !empty($matches[1])) {
1776 if (empty($images_dir)) {
1778 $this->error =
'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk';
1783 foreach ($matches[1] as $key => $ext) {
1785 $filecontent = $matches[2][$key];
1786 $cid =
'cid000'.dol_hash($this->html,
'md5');
1787 $destfiletmp = $images_dir.
'/'.$cid.
'.'.$ext;
1789 $fhandle = @fopen($destfiletmp,
'w');
1791 $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent));
1793 @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK));
1795 $this->errors[] =
"Failed to open file '".$destfiletmp.
"' for write";
1799 if (file_exists($destfiletmp)) {
1801 $this->html_images[$i][
"fullpath"] = $destfiletmp;
1803 $this->html_images[$i][
"name"] = basename($destfiletmp);
1805 $this->html_images[$i][
"content_type"] = $this->image_types[strtolower($ext)];
1807 $this->html_images[$i][
"cid"] = $cid;
1809 $this->html_images[$i][
"type"] =
'cidfromdata';
1811 $this->html = str_replace(
'src="data:image/'.$ext.
';base64,'.$filecontent.
'"',
'src="cid:'.$this->html_images[$i][
"cid"].
'"', $this->html);
1837 public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
1843 $arrayaddress = explode(
',', $address);
1847 foreach ($arrayaddress as $val) {
1849 if (preg_match(
'/^(.*)<(.*)>$/i', trim($val), $regs)) {
1850 $name = trim($regs[1]);
1851 $email = trim($regs[2]);
1854 $email = trim($val);
1862 $newemail = $name ? $name : $email;
1863 $newemail =
'<a href="mailto:'.$email.
'">'.$newemail.
'</a>';
1866 $newemail = $name ? $name : $email;
1871 if ($format == 1 || $format == 3) {
1872 $newemail =
'<'.$email.
'>';
1874 if ($format == 0 || $format == 3) {
1875 if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) {
1876 $newemail =
'<'.$email.
'>';
1878 $newemail =
'<'.$email.
'>';
1880 $newemail = ($format == 3 ?
'"' :
'').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ?
'"' :
'').
' <'.$email.
'>';
1884 $ret = ($ret ? $ret.
',' :
'').$newemail;
1887 if ($maxnumberofemail && $i >= $maxnumberofemail) {
1888 if (count($arrayaddress) > $maxnumberofemail) {
1912 $arrayaddress = explode(
',', $address);
1915 foreach ($arrayaddress as $val) {
1916 if (preg_match(
'/^(.*)<(.*)>$/i', trim($val), $regs)) {
1917 $name = trim($regs[1]);
1918 $email = trim($regs[2]);
1921 $email = trim($val);
1924 $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.
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)
Seearch 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_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_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.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) 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.