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();
116 public $filename_list = array();
120 public $mimetype_list = array();
124 public $mimefilename_list = array();
128 public $cid_list = array();
132 public $image_boundary;
133 public $atleastoneimage = 0;
134 public $html_images = array();
135 public $images_encoded = array();
136 public $image_types = array(
137 'gif' =>
'image/gif',
138 'jpg' =>
'image/jpeg',
139 'jpeg' =>
'image/jpeg',
140 'jpe' =>
'image/jpeg',
141 'bmp' =>
'image/bmp',
142 'png' =>
'image/png',
143 'tif' =>
'image/tiff',
144 'tiff' =>
'image/tiff',
170 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 =
'')
172 global $conf, $dolibarr_main_data_root, $user;
174 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);
175 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
179 if (is_array($mimefilename_list)) {
180 foreach ($mimefilename_list as $key => $val) {
187 $this->sendcontext = $sendcontext;
190 $this->sendmode =
'';
191 if (!empty($this->sendcontext)) {
192 $smtpContextKey = strtoupper($this->sendcontext);
194 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
195 $this->sendmode = $smtpContextSendMode;
198 if (empty($this->sendmode)) {
199 $this->sendmode = (!empty($conf->global->MAIN_MAIL_SENDMODE) ? $conf->global->MAIN_MAIL_SENDMODE :
'mail');
205 $this->eol2 =
"\r\n";
206 if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
209 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
213 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
216 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"), 3);
219 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"), 3);
221 if (empty($subject)) {
222 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
223 $this->error =
'ErrorSubjectIsRequired';
227 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
232 if ($msgishtml == -1) {
233 $this->msgishtml = 0;
235 $this->msgishtml = 1;
238 $this->msgishtml = $msgishtml;
241 global $dolibarr_main_url_root;
244 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
245 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
249 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
251 if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) {
252 $this->msgishtml = 1;
256 if ($this->msgishtml) {
260 if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) {
265 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
267 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
268 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
273 if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA)) {
277 if ($resultImageData<0) {
278 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData");
279 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
282 $findimg += $resultImageData;
287 foreach ($this->html_images as $i => $val) {
288 if ($this->html_images[$i]) {
289 $this->atleastoneimage = 1;
290 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
291 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
293 $posindice = count($filename_list);
294 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
295 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
296 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
298 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
301 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
303 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
312 if (is_array($filename_list)) {
313 foreach ($filename_list as $i => $val) {
314 if ($filename_list[$i]) {
315 $this->atleastonefile = 1;
316 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);
323 if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) {
324 $listofemailstoadd = explode(
',', $conf->global->MAIN_MAIL_AUTOCOPY_TO);
325 foreach ($listofemailstoadd as $key => $val) {
326 $emailtoadd = $listofemailstoadd[$key];
327 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
328 if (!empty($user) && !empty($user->email)) {
329 $emailtoadd = $user->email;
334 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
338 $listofemailstoadd[$key] = $emailtoadd;
340 unset($listofemailstoadd[$key]);
343 if (!empty($listofemailstoadd)) {
344 $addr_bcc .= ($addr_bcc ?
', ' :
'').join(
', ', $listofemailstoadd);
348 $this->subject = $subject;
354 $this->deliveryreceipt = $deliveryreceipt;
355 if (empty($replyto)) {
360 $this->trackid = $trackid;
362 $this->filename_list = $filename_list;
363 $this->mimetype_list = $mimetype_list;
364 $this->mimefilename_list = $mimefilename_list;
365 $this->cid_list = $cid_list;
367 if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) {
370 $this->addr_bcc =
'';
373 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
374 if (!empty($this->sendcontext)) {
375 $smtpContextKey = strtoupper($this->sendcontext);
377 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
378 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
382 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
386 if ($this->sendmode ==
'mail') {
397 if (!empty($moreinheader)) {
398 $smtp_headers .= $moreinheader;
404 if (!empty($this->html)) {
417 if (!empty($this->atleastonefile)) {
418 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
422 $this->headers = $smtp_headers.$mime_headers;
425 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
428 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
429 $this->message .= $text_body.$files_encoded;
430 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
431 } elseif ($this->sendmode ==
'smtps') {
435 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
436 $smtps =
new SMTPs();
437 $smtps->setCharSet($conf->file->character_set_client);
440 $subjecttouse = $this->subject;
445 $smtps->setSubject($subjecttouse);
448 $smtps->setTrackId($this->trackid);
451 if (!empty($moreinheader)) {
452 $smtps->setMoreInHeader($moreinheader);
455 if (!empty($this->html)) {
465 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
467 if ($this->msgishtml) {
468 $smtps->setBodyContent($msg,
'html');
470 $smtps->setBodyContent($msg,
'plain');
473 if ($this->atleastoneimage) {
474 foreach ($this->images_encoded as $img) {
475 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
479 if (!empty($this->atleastonefile)) {
480 foreach ($filename_list as $i => $val) {
481 $content = file_get_contents($filename_list[$i]);
482 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]);
486 $smtps->setCC($this->addr_cc);
487 $smtps->setBCC($this->addr_bcc);
488 $smtps->setErrorsTo($this->errors_to);
489 $smtps->setDeliveryReceipt($this->deliveryreceipt);
490 if (!empty($conf->global->$keyforsslseflsigned)) {
491 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
494 $host = dol_getprefix(
'email');
495 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
497 $this->smtps = $smtps;
498 } elseif ($this->sendmode ==
'swiftmailer') {
500 $host = dol_getprefix(
'email');
502 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
505 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
507 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
511 $this->message =
new Swift_Message();
514 $headers = $this->message->getHeaders();
515 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
516 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
517 $headerID = $this->msgid;
518 $msgid = $headers->get(
'Message-ID');
519 $msgid->setId($headerID);
520 $headers->addIdHeader(
'References', $headerID);
525 $result = $this->message->setSubject($this->subject);
527 $this->errors[] = $e->getMessage();
532 if (!empty($this->addr_from)) {
534 if (!empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) {
536 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
537 $adressEmailFrom = array();
538 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
539 $adressEmailFrom = reset($adressEmailFrom);
540 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
541 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
549 $this->errors[] = $e->getMessage();
554 if (!empty($this->addr_to)) {
558 $this->errors[] = $e->getMessage();
562 if (!empty($this->reply_to)) {
566 $this->errors[] = $e->getMessage();
571 $this->message->setCharSet($conf->file->character_set_client);
573 $this->errors[] = $e->getMessage();
576 if (!empty($this->html)) {
585 if ($this->atleastoneimage) {
586 foreach ($this->images_encoded as $img) {
588 $attachment = Swift_Image::fromPath($img[
'fullpath']);
590 $imgcid = $this->message->embed($attachment);
592 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
596 if ($this->msgishtml) {
597 $this->message->setBody($msg,
'text/html');
599 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
601 $this->message->setBody($msg,
'text/plain');
603 $this->message->addPart(
dol_nl2br($msg),
'text/html');
606 if (!empty($this->atleastonefile)) {
607 foreach ($filename_list as $i => $val) {
609 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
610 if (!empty($mimefilename_list[$i])) {
611 $attachment->setFilename($mimefilename_list[$i]);
613 $this->message->attach($attachment);
617 if (!empty($this->addr_cc)) {
621 $this->errors[] = $e->getMessage();
624 if (!empty($this->addr_bcc)) {
628 $this->errors[] = $e->getMessage();
632 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
634 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
636 $this->errors[] = $e->getMessage();
642 $this->error =
'Bad value for sendmode';
654 global $conf, $db, $langs;
656 $errorlevel = error_reporting();
661 if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
662 require_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
664 $hookmanager->initHooks(array(
'mail'));
666 $parameters = array();
668 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
670 $this->error =
"Error in hook maildao sendMail ".$reshook;
671 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
679 $sendingmode = $this->sendmode;
680 if ($this->sendcontext ==
'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode ==
'mail') {
682 $listofmethods = array();
683 $listofmethods[
'mail'] =
'PHP mail function';
685 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
689 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
690 $linktoadminemailend =
'</a>';
691 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
692 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
693 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
694 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
695 if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) {
696 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
697 $this->errors[] = $langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
703 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) {
704 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
706 $tmparray1 = explode(
',', $this->addr_to);
707 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
708 $this->error =
'Too much recipients in to:';
709 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
712 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) {
713 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
715 $tmparray2 = explode(
',', $this->addr_cc);
716 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
717 $this->error =
'Too much recipients in cc:';
718 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
721 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) {
722 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
724 $tmparray3 = explode(
',', $this->addr_bcc);
725 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
726 $this->error =
'Too much recipients in bcc:';
727 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
730 if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) {
731 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
733 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
734 $this->error =
'Too much recipients in to:, cc:, bcc:';
735 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
739 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
740 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
741 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
742 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
743 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
744 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
745 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
746 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
747 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
748 if (!empty($this->sendcontext)) {
749 $smtpContextKey = strtoupper($this->sendcontext);
751 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
752 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
753 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
754 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
755 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
756 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
757 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
758 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
759 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
760 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
765 if ($this->sendmode ==
'mail') {
768 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
769 dol_syslog(
"CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
773 if (isset($_SERVER[
"WINDIR"])) {
774 if (empty($this->addr_from)) {
775 $this->addr_from =
'robot@example.com';
777 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
782 if (!empty($conf->global->$keyforsmtpserver)) {
783 ini_set(
'SMTP', $conf->global->$keyforsmtpserver);
785 if (!empty($conf->global->$keyforsmtpport)) {
786 ini_set(
'smtp_port', $conf->global->$keyforsmtpport);
790 if ($res && !$this->subject) {
791 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
792 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
796 if ($res && !$dest) {
797 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
798 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
803 $additionnalparam =
'';
804 if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) {
809 $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) :
''));
811 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
812 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
815 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) {
816 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
820 if (preg_match(
'/^win/i', PHP_OS)) {
823 if (preg_match(
'/^mac/i', PHP_OS)) {
827 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
829 $this->message = stripslashes($this->message);
831 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
836 $subjecttouse = $this->subject;
841 if (!empty($additionnalparam)) {
842 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
844 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
848 $langs->load(
"errors");
849 $this->error =
"Failed to send mail with php mail";
851 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
853 $this->error .=
".<br>";
854 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
855 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
857 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
861 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
865 if (isset($_SERVER[
"WINDIR"])) {
866 @ini_restore(
'sendmail_from');
870 if (!empty($conf->global->$keyforsmtpserver)) {
873 if (!empty($conf->global->$keyforsmtpport)) {
874 ini_restore(
'smtp_port');
876 } elseif ($this->sendmode ==
'smtps') {
877 if (!is_object($this->smtps)) {
878 $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.";
879 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
885 $this->smtps->setTransportType(0);
888 if (empty($conf->global->$keyforsmtpserver)) {
889 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
891 if (empty($conf->global->$keyforsmtpport)) {
892 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
896 $server = $conf->global->$keyforsmtpserver;
898 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
901 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
904 $server = ($secure ? $secure.
'://' :
'').$server;
906 $port = $conf->global->$keyforsmtpport;
908 $this->smtps->setHost($server);
909 $this->smtps->setPort($port);
913 if (!empty($conf->global->$keyforsmtpid)) {
914 $loginid = $conf->global->$keyforsmtpid;
915 $this->smtps->setID($loginid);
917 if (!empty($conf->global->$keyforsmtppw)) {
918 $loginpass = $conf->global->$keyforsmtppw;
919 $this->smtps->setPW($loginpass);
923 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
925 $keyforsupportedoauth2array = $conf->global->$keyforsmtpoauthservice;
926 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
927 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
929 $keyforprovider =
'';
931 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
932 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
934 if (isset($supportedoauth2array)) {
935 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
937 $OAUTH_SERVICENAME =
'Unknown';
940 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
942 $storage =
new DoliStorage($db, $conf, $keyforprovider);
944 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
947 if (is_object($tokenobj)) {
948 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
951 if (is_object($tokenobj) && $expire) {
952 $credentials =
new Credentials(
957 $serviceFactory = new \OAuth\ServiceFactory();
958 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
960 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
962 $refreshtoken = $tokenobj->getRefreshToken();
963 $tokenobj = $apiService->refreshAccessToken($tokenobj);
964 $tokenobj->setRefreshToken($refreshtoken);
965 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
968 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
969 if (is_object($tokenobj)) {
970 $this->smtps->setToken($tokenobj->getAccessToken());
972 $this->error =
"Token not found";
976 $this->error = $e->getMessage();
977 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
982 $from = $this->smtps->getFrom(
'org');
983 if ($res && !$from) {
984 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - Sender address '$from' invalid";
985 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
988 $dest = $this->smtps->getTo();
989 if ($res && !$dest) {
990 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - Recipient address '$dest' invalid";
991 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
996 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
997 $this->smtps->setDebug(
true);
1000 $result = $this->smtps->sendMsg();
1002 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1007 $smtperrorcode = $this->smtps->lastretval;
1008 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1010 if ($smtperrorcode ==
'421') {
1025 $result = $this->smtps->getErrors();
1026 if (empty($this->error) && empty($result)) {
1027 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1030 if (empty($this->error)) {
1031 $this->error = $result;
1033 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=".$conf->global->$keyforsmtpport.
" - ".$this->error, LOG_ERR);
1036 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1041 } elseif ($this->sendmode ==
'swiftmailer') {
1044 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1047 if (empty($conf->global->$keyforsmtpserver)) {
1048 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1050 if (empty($conf->global->$keyforsmtpport)) {
1051 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1055 $server = $conf->global->$keyforsmtpserver;
1057 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1060 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1064 $this->transport =
new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
1066 if (!empty($conf->global->$keyforsmtpid)) {
1067 $this->transport->setUsername($conf->global->$keyforsmtpid);
1069 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1070 $this->transport->setPassword($conf->global->$keyforsmtppw);
1073 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1076 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1077 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1079 $keyforprovider =
'';
1081 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1082 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1084 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1086 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1088 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1091 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1094 if (is_object($tokenobj)) {
1095 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1098 if (is_object($tokenobj) && $expire) {
1099 $credentials =
new Credentials(
1104 $serviceFactory = new \OAuth\ServiceFactory();
1105 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1107 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1109 $refreshtoken = $tokenobj->getRefreshToken();
1110 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1111 $tokenobj->setRefreshToken($refreshtoken);
1112 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1114 if (is_object($tokenobj)) {
1115 $this->transport->setAuthMode(
'XOAUTH2');
1116 $this->transport->setPassword($tokenobj->getAccessToken());
1118 $this->errors[] =
"Token not found";
1122 $this->errors[] = $e->getMessage();
1123 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1126 if (!empty($conf->global->$keyforsslseflsigned)) {
1127 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1132 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1133 $this->message->setEncoder($contentEncoderBase64);
1136 $this->mailer =
new Swift_Mailer($this->transport);
1139 if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) {
1140 $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
1141 $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
1142 $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
1143 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1144 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1147 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1149 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1152 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1155 $failedRecipients = array();
1157 $result = $this->mailer->send($this->message, $failedRecipients);
1159 $this->errors[] = $e->getMessage();
1161 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1166 if (!empty($this->error) || !empty($this->errors) || !$result) {
1167 if (!empty($failedRecipients)) {
1168 $this->errors[] =
'Transport failed for the following addresses: "' . join(
'", "', $failedRecipients) .
'".';
1170 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1173 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1177 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1183 return 'Bad value for sendmode';
1187 foreach ($this->html_images as $val) {
1188 if (!empty($val[
'type']) && $val[
'type'] ==
'cidfromdata') {
1193 $parameters = array(
'sent' => $res);
1195 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1197 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1198 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1203 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1204 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1207 error_reporting($errorlevel);
1220 return '=?'.$conf->file->character_set_client.
'?B?'.base64_encode($stringtoencode).
'?=';
1235 if (is_readable($newsourcefile)) {
1236 $contents = file_get_contents($newsourcefile);
1237 $encoded = chunk_split(base64_encode($contents), 76, $this->eol);
1240 $this->error =
"Error in _encode_file() method: Can't read file '".$sourcefile.
"'";
1241 dol_syslog(
"CMailFile::_encode_file: ".$this->error, LOG_ERR);
1258 global $conf, $dolibarr_main_data_root;
1260 if (@is_writeable($dolibarr_main_data_root)) {
1261 $outputfile = $dolibarr_main_data_root.
"/dolibarr_mail.log";
1262 $fp = fopen($outputfile,
"w");
1264 if ($this->sendmode ==
'mail') {
1265 fputs($fp, $this->headers);
1266 fputs($fp, $this->eol);
1267 fputs($fp, $this->message);
1268 } elseif ($this->sendmode ==
'smtps') {
1269 fputs($fp, $this->smtps->log);
1270 } elseif ($this->sendmode ==
'swiftmailer') {
1271 fputs($fp, $this->logger->dump());
1275 if (!empty($conf->global->MAIN_UMASK)) {
1276 @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
1290 global $dolibarr_main_data_root;
1292 if (@is_writeable($dolibarr_main_data_root)) {
1293 $srcfile = $dolibarr_main_data_root.
"/dolibarr_mail.log";
1295 $destfile = $dolibarr_main_data_root.
"/dolibarr_mail.".
dol_print_date(
dol_now(),
'dayhourlog',
'gmt').
".err";
1297 $destfile = $dolibarr_main_data_root.
"/dolibarr_mail.err";
1300 dol_move($srcfile, $destfile, 0, 1, 0, 0);
1313 if (!preg_match(
'/^[\s\t]*<html/i', $msg)) {
1314 $out =
"<html><head><title></title>";
1315 if (!empty($this->styleCSS)) {
1318 $out .=
"</head><body";
1319 if (!empty($this->bodyCSS)) {
1324 $out .=
"</body></html>";
1339 if (!empty($this->css)) {
1341 $this->styleCSS =
'<style type="text/css">';
1342 $this->styleCSS .=
'body {';
1344 if ($this->css[
'bgcolor']) {
1345 $this->styleCSS .=
' background-color: '.$this->css[
'bgcolor'].
';';
1346 $this->bodyCSS .=
' bgcolor="'.$this->css[
'bgcolor'].
'"';
1348 if ($this->css[
'bgimage']) {
1350 $this->styleCSS .=
' background-image: url("cid:'.$this->css[
'bgimage_cid'].
'");';
1352 $this->styleCSS .=
'}';
1353 $this->styleCSS .=
'</style>';
1370 $host = dol_getprefix(
'email');
1374 $out .=
"From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
1375 if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
1376 $out .=
"To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
1379 $out .=
"Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
1380 if (isset($this->reply_to) && $this->reply_to) {
1381 $out .=
"Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
1383 if (isset($this->errors_to) && $this->errors_to) {
1384 $out .=
"Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1388 if (isset($this->addr_cc) && $this->addr_cc) {
1389 $out .=
"Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1391 if (isset($this->addr_bcc) && $this->addr_bcc) {
1392 $out .=
"Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2;
1396 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1397 $out .=
"Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1402 $out .=
'Date: '.date(
"r").$this->eol2;
1404 $trackid = $this->trackid;
1407 $this->msgid = time().
'.phpmail-dolibarr-'.$trackid.
'@'.$host;
1408 $out .=
'Message-ID: <'.$this->msgid.
">".$this->eol2;
1409 $out .=
'References: <'.$this->msgid.
">".$this->eol2;
1410 $out .=
'X-Dolibarr-TRACKID: '.$trackid.
'@'.$host.$this->eol2;
1412 $this->msgid = time().
'.phpmail@'.$host;
1413 $out .=
'Message-ID: <'.$this->msgid.
">".$this->eol2;
1416 if (!empty($_SERVER[
'REMOTE_ADDR'])) {
1417 $out .=
"X-RemoteAddr: ".$_SERVER[
'REMOTE_ADDR'].$this->eol2;
1419 $out .=
"X-Mailer: Dolibarr version ".DOL_VERSION.
" (using php mail)".$this->eol2;
1420 $out .=
"Mime-Version: 1.0".$this->eol2;
1424 $out .=
"Content-Type: multipart/mixed;".$this->eol2.
" boundary=\"".$this->mixed_boundary.
"\"".$this->eol2;
1425 $out .=
"Content-Transfer-Encoding: 8bit".$this->eol2;
1427 dol_syslog(
"CMailFile::write_smtpheaders smtp_header=\n".$out);
1446 if (is_array($filename_list)) {
1447 $filename_list_size = count($filename_list);
1448 for ($i = 0; $i < $filename_list_size; $i++) {
1449 if ($filename_list[$i]) {
1450 if ($mimefilename_list[$i]) {
1451 $filename_list[$i] = $mimefilename_list[$i];
1453 $out .=
"X-attachments: $filename_list[$i]".$this->eol2;
1458 dol_syslog(
"CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1476 $out .=
"--".$this->mixed_boundary.$this->eol;
1478 if ($this->atleastoneimage) {
1479 $out .=
"Content-Type: multipart/alternative;".$this->eol.
" boundary=\"".$this->alternative_boundary.
"\"".$this->eol;
1481 $out .=
"--".$this->alternative_boundary.$this->eol;
1485 $strContent = preg_replace(
"/(?<!\r)\n/si",
"\r\n", $msgtext);
1486 if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
1487 $strContent = preg_replace(
"/\r\n/si",
"\n", $strContent);
1490 $strContentAltText =
'';
1491 if ($this->msgishtml) {
1493 $strContentAltText = preg_replace(
"/<br\s*[^>]*>/",
" ", $strContent);
1495 $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1496 $strContentAltText = trim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ?
"\r\n" :
"\n"));
1505 $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ?
"\r\n" :
"\n"));
1507 if ($this->msgishtml) {
1508 if ($this->atleastoneimage) {
1509 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1511 $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol;
1512 $out .=
"--".$this->alternative_boundary.$this->eol;
1513 $out .=
"Content-Type: multipart/related;".$this->eol.
" boundary=\"".$this->related_boundary.
"\"".$this->eol;
1515 $out .=
"--".$this->related_boundary.$this->eol;
1518 if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1519 $out .=
"Content-Type: multipart/alternative;".$this->eol.
" boundary=\"".$this->alternative_boundary.
"\"".$this->eol;
1521 $out .=
"--".$this->alternative_boundary.$this->eol;
1522 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1524 $out .= $this->eol.$strContentAltText.$this->eol;
1525 $out .=
"--".$this->alternative_boundary.$this->eol;
1528 $out .=
"Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1530 $out .= $this->eol.$strContent.$this->eol;
1532 if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1533 $out .=
"--".$this->alternative_boundary.
"--".$this->eol;
1536 $out .=
"Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1538 $out .= $this->eol.$strContent.$this->eol;
1544 if ($this->atleastoneimage) {
1547 $out .=
"--".$this->related_boundary.
"--".$this->eol;
1548 $out .= $this->eol.
"--".$this->alternative_boundary.
"--".$this->eol;
1565 private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
1570 $filename_list_size = count($filename_list);
1571 for ($i = 0; $i < $filename_list_size; $i++) {
1572 if ($filename_list[$i]) {
1575 if ($encoded >= 0) {
1576 if ($mimefilename_list[$i]) {
1577 $filename_list[$i] = $mimefilename_list[$i];
1579 if (!$mimetype_list[$i]) {
1580 $mimetype_list[$i] =
"application/octet-stream";
1583 $out .=
"--".$this->mixed_boundary.$this->eol;
1584 $out .=
"Content-Disposition: attachment; filename=\"".$filename_list[$i].
"\"".$this->eol;
1585 $out .=
"Content-Type: ".$mimetype_list[$i].
"; name=\"".$filename_list[$i].
"\"".$this->eol;
1586 $out .=
"Content-Transfer-Encoding: base64".$this->eol;
1587 $out .=
"Content-Description: ".$filename_list[$i].$this->eol;
1588 if (!empty($cidlist) && is_array($cidlist) && $cidlist[$i]) {
1589 $out .=
"X-Attachment-Id: ".$cidlist[$i].$this->eol;
1590 $out .=
"Content-ID: <".$cidlist[$i].
'>'.$this->eol;
1618 if (is_array($images_list)) {
1619 foreach ($images_list as $img) {
1620 dol_syslog(
"CMailFile::write_images: ".$img[
"name"]);
1622 $out .=
"--".$this->related_boundary.$this->eol;
1623 $out .=
"Content-Type: ".$img[
"content_type"].
"; name=\"".$img[
"name"].
"\"".$this->eol;
1624 $out .=
"Content-Transfer-Encoding: base64".$this->eol;
1625 $out .=
"Content-Disposition: inline; filename=\"".$img[
"name"].
"\"".$this->eol;
1626 $out .=
"Content-ID: <".$img[
"cid"].
">".$this->eol;
1628 $out .= $img[
"image_encoded"];
1653 if (function_exists(
'fsockopen')) {
1654 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
1655 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
1656 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
1657 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
1658 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
1659 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
1660 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
1661 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
1662 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
1664 if (!empty($this->sendcontext)) {
1665 $smtpContextKey = strtoupper($this->sendcontext);
1667 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
1668 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
1669 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
1670 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
1671 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
1672 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
1673 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
1674 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
1675 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
1676 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
1681 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1682 $host =
'ssl://'.$host;
1687 dol_syslog(
"Try socket connection to host=".$host.
" port=".$port);
1689 $errno = 0; $errstr =
'';
1690 if ($socket = @fsockopen(
1698 if (function_exists(
'stream_set_timeout')) {
1699 stream_set_timeout($socket, $timeout, 0);
1709 $this->error =
utf8_check(
'Error '.$errno.
' - '.$errstr) ?
'Error '.$errno.
' - '.$errstr : utf8_encode(
'Error '.$errno.
' - '.$errstr);
1728 $server_response =
'';
1730 while (substr($server_response, 3, 1) !=
' ') {
1731 if (!($server_response = fgets($socket, 256))) {
1732 $this->error =
"Couldn't get mail server response codes";
1737 if (!(substr($server_response, 0, 3) == $response)) {
1738 $this->error =
"Ran into problems sending Mail.\r\nResponse: $server_response";
1754 $extensions = array_keys($this->image_types);
1760 preg_match_all(
'/(?:"|\')([^"\']+\.('.implode(
'|', $extensions).
'))(?:"|\')/Ui', $this->html, $matches);
1762 if (!empty($matches) && !empty($matches[1])) {
1765 foreach ($matches[1] as $full) {
1767 if (preg_match(
'/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) {
1770 if (file_exists($images_dir.
'/'.$img)) {
1772 $src = preg_quote($full,
'/');
1774 $this->html_images[$i][
"fullpath"] = $images_dir.
'/'.$img;
1776 $this->html_images[$i][
"name"] = $img;
1779 if (preg_match(
'/^.+\.(\w{3,4})$/', $img, $regext)) {
1780 $ext = strtolower($regext[1]);
1781 $this->html_images[$i][
"content_type"] = $this->image_types[$ext];
1784 $this->html_images[$i][
"cid"] =
dol_hash($this->html_images[$i][
"fullpath"],
'md5');
1786 $this->html_images[$i][
"type"] =
'cidfromurl';
1788 $this->html = preg_replace(
"/src=\"$src\"|src='$src'/i",
"src=\"cid:".$this->html_images[$i][
"cid"].
"\"", $this->html);
1794 if (!empty($this->html_images)) {
1799 foreach ($this->html_images as $img) {
1800 $fullpath = $images_dir.
'/'.$img[
"name"];
1803 if (!in_array($fullpath, $inline)) {
1805 if ($image = file_get_contents($fullpath)) {
1808 preg_match(
'/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img[
"name"], $regs);
1809 $imgName = $regs[1];
1811 $this->images_encoded[$i][
'name'] = $imgName;
1812 $this->images_encoded[$i][
'fullpath'] = $fullpath;
1813 $this->images_encoded[$i][
'content_type'] = $img[
"content_type"];
1814 $this->images_encoded[$i][
'cid'] = $img[
"cid"];
1816 $this->images_encoded[$i][
"image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1817 $inline[] = $fullpath;
1844 $extensions = array_keys($this->image_types);
1846 if ($images_dir && !
dol_is_dir($images_dir)) {
1863 preg_match_all(
'/src="data:image\/('.implode(
'|', $extensions).
');base64,([^"]+)"/Ui', $this->html, $matches);
1865 if (!empty($matches) && !empty($matches[1])) {
1866 if (empty($images_dir)) {
1868 $this->error =
'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk';
1872 $i = count($this->html_images);
1873 foreach ($matches[1] as $key => $ext) {
1875 $filecontent = $matches[2][$key];
1877 $cid =
'cid000'.dol_hash($filecontent,
'md5');
1879 $destfiletmp = $images_dir.
'/'.$cid.
'.'.$ext;
1882 dol_syslog(
"write the cid file ".$destfiletmp);
1883 $fhandle = @fopen($destfiletmp,
'w');
1885 $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent));
1887 @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK));
1889 $this->errors[] =
"Failed to open file '".$destfiletmp.
"' for write";
1894 if (file_exists($destfiletmp)) {
1896 $this->html_images[$i][
"fullpath"] = $destfiletmp;
1898 $this->html_images[$i][
"name"] = basename($destfiletmp);
1900 $this->html_images[$i][
"content_type"] = $this->image_types[strtolower($ext)];
1902 $this->html_images[$i][
"cid"] = $cid;
1904 $this->html_images[$i][
"type"] =
'cidfromdata';
1906 $this->html = str_replace(
'src="data:image/'.$ext.
';base64,'.$filecontent.
'"',
'src="cid:'.$this->html_images[$i][
"cid"].
'"', $this->html);
1932 public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
1938 $arrayaddress = explode(
',', $address);
1942 foreach ($arrayaddress as $val) {
1944 if (preg_match(
'/^(.*)<(.*)>$/i', trim($val), $regs)) {
1945 $name = trim($regs[1]);
1946 $email = trim($regs[2]);
1949 $email = trim($val);
1957 $newemail = $name ? $name : $email;
1958 $newemail =
'<a href="mailto:'.$email.
'">'.$newemail.
'</a>';
1961 $newemail = $name ? $name : $email;
1966 if ($format == 1 || $format == 3) {
1967 $newemail =
'<'.$email.
'>';
1969 if ($format == 0 || $format == 3) {
1970 if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) {
1971 $newemail =
'<'.$email.
'>';
1973 $newemail =
'<'.$email.
'>';
1975 $newemail = ($format == 3 ?
'"' :
'').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ?
'"' :
'').
' <'.$email.
'>';
1979 $ret = ($ret ? $ret.
',' :
'').$newemail;
1982 if ($maxnumberofemail && $i >= $maxnumberofemail) {
1983 if (count($arrayaddress) > $maxnumberofemail) {
2007 $arrayaddress = explode(
',', $address);
2010 foreach ($arrayaddress as $val) {
2011 if (preg_match(
'/^(.*)<(.*)>$/i', trim($val), $regs)) {
2012 $name = trim($regs[1]);
2013 $email = trim($regs[2]);
2016 $email = trim($val);
2019 $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.
save_dump_mail_in_err()
Save content if mail is in error Used for debugging.
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_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
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).
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.
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.