192 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 =
'', $in_reply_to =
'', $references =
'')
194 global $conf, $dolibarr_main_data_root, $user;
196 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");
197 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
201 if (is_array($mimefilename_list)) {
202 foreach ($mimefilename_list as $key => $val) {
209 $this->sendcontext = $sendcontext;
212 $this->sendmode =
'';
213 if (!empty($this->sendcontext)) {
214 $smtpContextKey = strtoupper($this->sendcontext);
216 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
217 $this->sendmode = $smtpContextSendMode;
220 if (empty($this->sendmode)) {
230 $moreinheader .=
"Feedback-ID: ".$trackid.
':'.dol_getprefix(
'email').
":dolib\r\n";
236 $this->eol2 =
"\r\n";
240 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
244 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
247 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"), 3);
250 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"), 3);
252 if (empty($subject)) {
253 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
254 $this->error =
'ErrorSubjectIsRequired';
258 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
263 if ($msgishtml == -1) {
264 $this->msgishtml = 0;
266 $this->msgishtml = 1;
269 $this->msgishtml = $msgishtml;
272 global $dolibarr_main_url_root;
275 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
276 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
280 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
283 $this->msgishtml = 1;
285 dol_syslog(
"CMailFile::CMailfile: msgishtml=".$this->msgishtml, LOG_DEBUG);
288 if ($this->msgishtml) {
297 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
299 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
300 $this->error =
'ErrorInAddAttachmentsImageBaseOnMedia';
309 if ($resultImageData < 0) {
310 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
311 $this->error =
'ErrorInAddAttachmentsImageBaseIsSrcData';
314 $findimg += $resultImageData;
319 foreach ($this->html_images as $i => $val) {
320 if ($this->html_images[$i]) {
321 $this->atleastoneimage = 1;
322 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
323 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
325 $posindice = count($filename_list);
326 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
327 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
328 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
330 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
333 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
335 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
344 if (is_array($filename_list)) {
345 foreach ($filename_list as $i => $val) {
346 if ($filename_list[$i]) {
347 $this->atleastonefile = 1;
348 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]=".(empty($cid_list[$i]) ?
'' : $cid_list[$i]), LOG_DEBUG);
357 foreach ($listofemailstoadd as $key => $val) {
358 $emailtoadd = $listofemailstoadd[$key];
359 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
360 if (!empty($user) && !empty($user->email)) {
361 $emailtoadd = $user->email;
366 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
370 $listofemailstoadd[$key] = $emailtoadd;
372 unset($listofemailstoadd[$key]);
375 if (!empty($listofemailstoadd)) {
376 $addr_bcc .= ($addr_bcc ?
', ' :
'').implode(
', ', $listofemailstoadd);
383 $listofemailstonotsendto = explode(
',',
getDolGlobalString(
'MAIN_MAIL_FORCE_NOT_SENDING_TO'));
387 $tabto = explode(
",", $to);
388 foreach ($tabto as $key => $addrto) {
390 if (in_array($addrto[0], $listofemailstonotsendto)) {
398 $to = implode(
',', $tabto);
402 $tabcc = explode(
',', $addr_cc);
403 foreach ($tabcc as $key => $cc) {
405 if (in_array($cc[0], $listofemailstonotsendto)) {
413 $addr_cc = implode(
',', $tabcc);
417 $tabbcc = explode(
',', $addr_bcc);
418 foreach ($tabbcc as $key => $bcc) {
420 if (in_array($bcc[0], $listofemailstonotsendto)) {
421 unset($tabbcc[$key]);
428 $addr_bcc = implode(
',', $tabbcc);
432 if (empty($replyto)) {
440 $this->subject = $subject;
446 $this->deliveryreceipt = $deliveryreceipt;
449 $this->trackid = $trackid;
450 $this->in_reply_to = $in_reply_to;
451 $this->references = $references;
453 $this->filename_list = $filename_list;
454 $this->mimetype_list = $mimetype_list;
455 $this->mimefilename_list = $mimefilename_list;
456 $this->cid_list = $cid_list;
461 $this->addr_bcc =
'';
464 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
465 if (!empty($this->sendcontext)) {
466 $smtpContextKey = strtoupper($this->sendcontext);
468 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
469 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
473 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
477 if ($this->sendmode ==
'mail') {
488 if (!empty($moreinheader)) {
489 $smtp_headers .= $moreinheader;
495 if (!empty($this->html)) {
508 if (!empty($this->atleastonefile)) {
509 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
513 $this->headers = $smtp_headers.$mime_headers;
516 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
519 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
520 $this->message .= $text_body.$files_encoded;
521 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
522 } elseif ($this->sendmode ==
'smtps') {
525 $host = dol_getprefix(
'email');
527 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
528 $smtps =
new SMTPs();
529 $smtps->setCharSet($conf->file->character_set_client);
532 $subjecttouse = $this->subject;
537 $smtps->setSubject($subjecttouse);
542 $smtps->setTrackId($this->trackid);
544 if (!empty($this->in_reply_to)) {
545 $smtps->setInReplyTo($this->in_reply_to);
547 if (!empty($this->references)) {
548 $smtps->setReferences($this->references);
551 if (!empty($moreinheader)) {
552 $smtps->setMoreInHeader($moreinheader);
557 if (!empty($this->html)) {
567 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
569 if ($this->msgishtml) {
570 $smtps->setBodyContent($msg,
'html');
572 $smtps->setBodyContent($msg,
'plain');
575 if ($this->atleastoneimage) {
576 foreach ($this->images_encoded as $img) {
577 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
581 if (!empty($this->atleastonefile)) {
582 foreach ($filename_list as $i => $val) {
583 $content = file_get_contents($filename_list[$i]);
584 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], (empty($cid_list[$i]) ?
'' : $cid_list[$i]));
588 $smtps->setCC($this->addr_cc);
589 $smtps->setBCC($this->addr_bcc);
590 $smtps->setErrorsTo($this->errors_to);
591 $smtps->setDeliveryReceipt($this->deliveryreceipt);
593 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
596 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
598 $this->smtps = $smtps;
599 } elseif ($this->sendmode ==
'swiftmailer') {
602 $host = dol_getprefix(
'email');
604 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
607 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
609 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
613 $this->message =
new Swift_Message();
616 $headers = $this->message->getHeaders();
618 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
619 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
620 $headerID = $this->msgid;
621 $msgid = $headers->get(
'Message-ID');
622 $msgid->setId($headerID);
625 if (!empty($this->in_reply_to)) {
626 $headers->addIdHeader(
'In-Reply-To', $this->in_reply_to);
629 if (!empty($this->references)) {
630 $headers->addIdHeader(
'References', $this->references);
633 if (!empty($moreinheader)) {
634 $moreinheaderarray = preg_split(
'/[\r\n]+/', $moreinheader);
635 foreach ($moreinheaderarray as $moreinheaderval) {
636 $moreinheadervaltmp = explode(
':', $moreinheaderval, 2);
637 if (!empty($moreinheadervaltmp[0]) && !empty($moreinheadervaltmp[1])) {
638 $headers->addTextHeader($moreinheadervaltmp[0], $moreinheadervaltmp[1]);
645 $this->message->setSubject($this->subject);
647 $this->errors[] = $e->getMessage();
652 if (!empty($this->addr_from)) {
656 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
657 $adressEmailFrom = array();
658 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
659 $adressEmailFrom = reset($adressEmailFrom);
660 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
661 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
669 $this->errors[] = $e->getMessage();
674 if (!empty($this->addr_to)) {
678 $this->errors[] = $e->getMessage();
682 if (!empty($this->reply_to)) {
686 $this->errors[] = $e->getMessage();
690 if (!empty($this->errors_to)) {
692 $headers->addTextHeader(
'Errors-To', $this->
getValidAddress($this->errors_to, 0));
694 $this->errors[] = $e->getMessage();
699 $this->message->setCharSet($conf->file->character_set_client);
701 $this->errors[] = $e->getMessage();
704 if (!empty($this->html)) {
713 if ($this->atleastoneimage) {
714 foreach ($this->html_images as $img) {
716 $attachment = Swift_Image::fromPath($img[
'fullpath']);
718 $imgcid = $this->message->embed($attachment);
720 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
722 foreach ($this->images_encoded as $img) {
724 $attachment = Swift_Image::fromPath($img[
'fullpath']);
726 $imgcid = $this->message->embed($attachment);
728 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
732 if ($this->msgishtml) {
733 $this->message->setBody($msg,
'text/html');
735 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
737 $this->message->setBody($msg,
'text/plain');
739 $this->message->addPart(
dol_nl2br($msg),
'text/html');
742 if (!empty($this->atleastonefile)) {
743 foreach ($filename_list as $i => $val) {
745 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
746 if (!empty($mimefilename_list[$i])) {
747 $attachment->setFilename($mimefilename_list[$i]);
749 $this->message->attach($attachment);
753 if (!empty($this->addr_cc)) {
757 $this->errors[] = $e->getMessage();
760 if (!empty($this->addr_bcc)) {
764 $this->errors[] = $e->getMessage();
767 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
769 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
771 $this->errors[] = $e->getMessage();
777 $this->error =
'Bad value for sendmode';
790 global $conf, $db, $langs, $hookmanager;
792 $errorlevel = error_reporting();
798 if (!is_object($hookmanager)) {
799 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
802 $hookmanager->initHooks(array(
'mail'));
804 $parameters = array();
806 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
808 $this->error =
"Error in hook maildao sendMail ".$reshook;
809 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
817 $sendingmode = $this->sendmode;
818 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
820 $listofmethods = array();
821 $listofmethods[
'mail'] =
'PHP mail function';
823 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
827 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
828 $linktoadminemailend =
'</a>';
829 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
830 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
831 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
832 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
834 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
835 $this->errors[] = $langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
838 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
844 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
846 $tmparray1 = explode(
',', $this->addr_to);
847 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
848 $this->error =
'Too much recipients in to:';
849 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
853 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
855 $tmparray2 = explode(
',', $this->addr_cc);
856 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
857 $this->error =
'Too much recipients in cc:';
858 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
862 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
864 $tmparray3 = explode(
',', $this->addr_bcc);
865 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
866 $this->error =
'Too much recipients in bcc:';
867 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
871 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
873 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
874 $this->error =
'Too much recipients in to:, cc:, bcc:';
875 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
879 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
880 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
881 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
882 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
883 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
884 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
885 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
886 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
887 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
888 if (!empty($this->sendcontext)) {
889 $smtpContextKey = strtoupper($this->sendcontext);
891 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
892 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
893 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
894 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
895 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
896 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
897 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
898 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
899 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
900 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
905 if ($this->sendmode ==
'mail') {
908 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_NOTICE);
913 if (isset($_SERVER[
"WINDIR"])) {
914 if (empty($this->addr_from)) {
915 $this->addr_from =
'robot@example.com';
917 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
930 if ($res && !$this->subject) {
931 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
932 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
936 if ($res && !$dest) {
937 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
938 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
943 $additionnalparam =
'';
950 $additionnalparam .= ($additionnalparam ?
' ' :
'').(
getDolGlobalString(
'MAIN_MAIL_ERRORS_TO') ?
'-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from !=
'' ?
'-f'.$this->getValidAddress($this->addr_from, 2) :
''));
953 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
957 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
961 if (preg_match(
'/^win/i', PHP_OS)) {
964 if (preg_match(
'/^mac/i', PHP_OS)) {
968 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
970 $this->message = stripslashes($this->message);
977 $subjecttouse = $this->subject;
982 if (!empty($additionnalparam)) {
983 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
985 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
989 $langs->load(
"errors");
990 $this->error =
"Failed to send mail with php mail";
992 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
994 $this->error .=
".<br>";
995 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
996 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1002 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1006 if (isset($_SERVER[
"WINDIR"])) {
1007 @ini_restore(
'sendmail_from');
1012 ini_restore(
'SMTP');
1015 ini_restore(
'smtp_port');
1017 } elseif ($this->sendmode ==
'smtps') {
1018 if (!is_object($this->smtps)) {
1019 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1020 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1026 $this->smtps->setTransportType(0);
1029 if (empty($conf->global->$keyforsmtpserver)) {
1030 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1032 if (empty($conf->global->$keyforsmtpport)) {
1033 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1039 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1042 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1045 $server = ($secure ? $secure.
'://' :
'').$server;
1049 $this->smtps->setHost($server);
1050 $this->smtps->setPort($port);
1054 if (!empty($conf->global->$keyforsmtpid)) {
1056 $this->smtps->setID($loginid);
1058 if (!empty($conf->global->$keyforsmtppw)) {
1060 $this->smtps->setPW($loginpass);
1064 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1069 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1070 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1072 $keyforprovider =
'';
1074 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1075 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1077 if (!empty($supportedoauth2array)) {
1078 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1079 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1080 $OAUTH_SERVICENAME = $nameofservice;
1082 $OAUTH_SERVICENAME =
'Unknown';
1085 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1087 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1089 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1091 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1095 if (is_object($tokenobj)) {
1096 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1099 if (is_object($tokenobj) && $expire) {
1100 $credentials =
new Credentials(
1105 $serviceFactory = new \OAuth\ServiceFactory();
1106 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1108 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1110 $refreshtoken = $tokenobj->getRefreshToken();
1111 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1112 $tokenobj->setRefreshToken($refreshtoken);
1113 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1115 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1118 if (is_object($tokenobj)) {
1119 $this->smtps->setToken($tokenobj->getAccessToken());
1121 $this->error =
"Token not found";
1125 $this->error = $e->getMessage();
1126 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1131 $from = $this->smtps->getFrom(
'org');
1132 if ($res && !$from) {
1133 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1134 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1137 $dest = $this->smtps->getTo();
1138 if ($res && !$dest) {
1139 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1140 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1148 $this->smtps->setDebug(
true);
1151 $result = $this->smtps->sendMsg();
1159 $smtperrorcode = $this->smtps->lastretval;
1160 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1162 if ($smtperrorcode ==
'421') {
1177 $result = $this->smtps->getErrors();
1178 if (empty($this->error) && empty($result)) {
1179 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1182 if (empty($this->error)) {
1183 $this->error = $result;
1185 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1193 } elseif ($this->sendmode ==
'swiftmailer') {
1196 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1199 if (empty($conf->global->$keyforsmtpserver)) {
1200 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1202 if (empty($conf->global->$keyforsmtpport)) {
1203 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1209 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1212 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1216 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalString($keyforsmtpport), $secure);
1218 if (!empty($conf->global->$keyforsmtpid)) {
1221 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1225 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1230 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1231 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1233 $keyforprovider =
'';
1235 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1236 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1238 if (!empty($supportedoauth2array)) {
1239 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1240 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1241 $OAUTH_SERVICENAME = $nameofservice;
1243 $OAUTH_SERVICENAME =
'Unknown';
1246 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1248 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1250 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1253 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1257 if (is_object($tokenobj)) {
1258 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1261 if (is_object($tokenobj) && $expire) {
1262 $credentials =
new Credentials(
1267 $serviceFactory = new \OAuth\ServiceFactory();
1268 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1270 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1272 $refreshtoken = $tokenobj->getRefreshToken();
1273 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1274 $tokenobj->setRefreshToken($refreshtoken);
1275 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1277 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1280 if (is_object($tokenobj)) {
1281 $this->transport->setAuthMode(
'XOAUTH2');
1282 $this->transport->setPassword($tokenobj->getAccessToken());
1284 $this->errors[] =
"Token not found";
1288 $this->errors[] = $e->getMessage();
1289 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1293 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1298 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1299 $this->message->setEncoder($contentEncoderBase64);
1302 $this->mailer =
new Swift_Mailer($this->transport);
1309 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1310 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1315 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1318 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1324 $failedRecipients = array();
1326 $result = $this->mailer->send($this->message, $failedRecipients);
1328 $this->errors[] = $e->getMessage();
1335 if (!empty($this->error) || !empty($this->errors) || !$result) {
1336 if (!empty($failedRecipients)) {
1337 $this->error =
'Transport failed for the following addresses: "' . implode(
'", "', $failedRecipients) .
'".';
1338 $this->errors[] = $this->error;
1340 dol_syslog(
"CMailFile::sendfile: mail end error=". implode(
' ', $this->errors), LOG_ERR);
1347 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1353 $this->error =
'Bad value for sendmode';
1358 foreach ($this->html_images as $val) {
1359 if (!empty($val[
'type']) && $val[
'type'] ==
'cidfromdata') {
1364 $parameters = array(
'sent' => $res);
1366 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1368 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1369 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1374 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1375 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1378 error_reporting($errorlevel);