228 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 =
'')
230 global $conf, $dolibarr_main_data_root, $user;
232 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");
233 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
237 if (is_array($mimefilename_list)) {
238 foreach ($mimefilename_list as $key => $val) {
245 $this->sendcontext = $sendcontext;
248 $this->sendmode =
'';
249 if (!empty($this->sendcontext)) {
250 $smtpContextKey = strtoupper($this->sendcontext);
252 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
253 $this->sendmode = $smtpContextSendMode;
256 if (empty($this->sendmode)) {
266 $moreinheader .=
"Feedback-ID: ".$trackid.
':'.dol_getprefix(
'email').
":dolib\r\n";
272 $this->eol2 =
"\r\n";
276 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
280 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
283 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"),
'3');
286 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"),
'3');
288 if (empty($subject)) {
289 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
290 $this->error =
'ErrorSubjectIsRequired';
294 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
299 if ($msgishtml == -1) {
300 $this->msgishtml = 0;
302 $this->msgishtml = 1;
305 $this->msgishtml = $msgishtml;
308 global $dolibarr_main_url_root;
311 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
312 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
316 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
319 $this->msgishtml = 1;
321 dol_syslog(
"CMailFile::CMailfile: msgishtml=".$this->msgishtml, LOG_DEBUG);
324 if ($this->msgishtml) {
333 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
335 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
336 $this->error =
'ErrorInAddAttachmentsImageBaseOnMedia';
345 if ($resultImageData < 0) {
346 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
347 $this->error =
'ErrorInAddAttachmentsImageBaseIsSrcData';
350 $findimg += $resultImageData;
355 foreach ($this->html_images as $i => $val) {
356 if ($this->html_images[$i]) {
357 $this->atleastoneimage = 1;
358 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
359 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
361 $posindice = count($filename_list);
362 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
363 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
364 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
366 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
369 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
371 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
380 if (is_array($filename_list)) {
381 foreach ($filename_list as $i => $val) {
382 if ($filename_list[$i]) {
383 $this->atleastonefile = 1;
384 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);
393 foreach ($listofemailstoadd as $key => $val) {
394 $emailtoadd = $listofemailstoadd[$key];
395 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
396 if (!empty($user) && !empty($user->email)) {
397 $emailtoadd = $user->email;
402 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
406 $listofemailstoadd[$key] = $emailtoadd;
408 unset($listofemailstoadd[$key]);
411 if (!empty($listofemailstoadd)) {
412 $addr_bcc .= ($addr_bcc ?
', ' :
'').implode(
', ', $listofemailstoadd);
420 $tabto = explode(
",", $to);
421 $listofemailstonotsendto = explode(
',',
getDolGlobalString(
'MAIN_MAIL_FORCE_NOT_SENDING_TO'));
422 foreach ($tabto as $key => $addrto) {
424 if (in_array($addrto[0], $listofemailstonotsendto)) {
432 $to = implode(
',', $tabto);
436 $tabcc = explode(
',', $addr_cc);
437 foreach ($tabcc as $key => $cc) {
439 if (in_array($cc[0], $listofemailstonotsendto)) {
447 $addr_cc = implode(
',', $tabcc);
451 $tabbcc = explode(
',', $addr_bcc);
452 foreach ($tabbcc as $key => $bcc) {
454 if (in_array($bcc[0], $listofemailstonotsendto)) {
455 unset($tabbcc[$key]);
462 $addr_bcc = implode(
',', $tabbcc);
466 if (empty($replyto)) {
474 $this->subject = $subject;
480 $this->deliveryreceipt = $deliveryreceipt;
483 $this->trackid = $trackid;
484 $this->in_reply_to = $in_reply_to;
485 $this->references = $references;
487 $this->filename_list = $filename_list;
488 $this->mimetype_list = $mimetype_list;
489 $this->mimefilename_list = $mimefilename_list;
490 $this->cid_list = $cid_list;
495 $this->addr_bcc =
'';
498 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
499 if (!empty($this->sendcontext)) {
500 $smtpContextKey = strtoupper($this->sendcontext);
502 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
503 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
507 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
511 if ($this->sendmode ==
'mail') {
522 if (!empty($moreinheader)) {
523 $smtp_headers .= $moreinheader;
529 if (!empty($this->html)) {
542 if (!empty($this->atleastonefile)) {
543 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
547 $this->headers = $smtp_headers.$mime_headers;
550 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
553 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
554 $this->message .= $text_body.$files_encoded;
555 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
556 } elseif ($this->sendmode ==
'smtps') {
559 $host = dol_getprefix(
'email');
561 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
562 $smtps =
new SMTPs();
563 $smtps->setCharSet($conf->file->character_set_client);
566 $subjecttouse = $this->subject;
571 $smtps->setSubject($subjecttouse);
576 $smtps->setTrackId($this->trackid);
578 if (!empty($this->in_reply_to)) {
579 $smtps->setInReplyTo($this->in_reply_to);
581 if (!empty($this->references)) {
582 $smtps->setReferences($this->references);
585 if (!empty($moreinheader)) {
586 $smtps->setMoreInHeader($moreinheader);
591 if (!empty($this->html)) {
604 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
606 if ($this->msgishtml) {
607 $smtps->setBodyContent($msg,
'html');
609 $smtps->setBodyContent($msg,
'plain');
612 if ($this->atleastoneimage) {
613 foreach ($this->images_encoded as $img) {
614 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
618 if (!empty($this->atleastonefile)) {
619 foreach ($filename_list as $i => $val) {
620 $content = file_get_contents($filename_list[$i]);
621 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], (empty($cid_list[$i]) ?
'' : $cid_list[$i]));
625 $smtps->setCC($this->addr_cc);
626 $smtps->setBCC($this->addr_bcc);
627 $smtps->setErrorsTo($this->errors_to);
628 $smtps->setDeliveryReceipt($this->deliveryreceipt);
630 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
633 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
635 $this->smtps = $smtps;
636 } elseif ($this->sendmode ==
'swiftmailer') {
639 $host = dol_getprefix(
'email');
641 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
644 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
646 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
650 $this->message =
new Swift_Message();
653 $headers = $this->message->getHeaders();
655 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
656 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
657 $headerID = $this->msgid;
658 $msgid = $headers->get(
'Message-ID');
659 if ($msgid instanceof Swift_Mime_Headers_IdentificationHeader) {
660 $msgid->setId($headerID);
664 if (!empty($this->in_reply_to)) {
665 $headers->addIdHeader(
'In-Reply-To', $this->in_reply_to);
668 if (!empty($this->references)) {
669 $headers->addIdHeader(
'References', $this->references);
672 if (!empty($moreinheader)) {
673 $moreinheaderarray = preg_split(
'/[\r\n]+/', $moreinheader);
674 foreach ($moreinheaderarray as $moreinheaderval) {
675 $moreinheadervaltmp = explode(
':', $moreinheaderval, 2);
676 if (!empty($moreinheadervaltmp[0]) && !empty($moreinheadervaltmp[1])) {
677 $headers->addTextHeader($moreinheadervaltmp[0], $moreinheadervaltmp[1]);
684 $this->message->setSubject($this->subject);
686 $this->errors[] = $e->getMessage();
691 if (!empty($this->addr_from)) {
695 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
696 $adressEmailFrom = array();
697 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
698 $adressEmailFrom = reset($adressEmailFrom);
699 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
700 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
708 $this->errors[] = $e->getMessage();
713 if (!empty($this->addr_to)) {
717 $this->errors[] = $e->getMessage();
721 if (!empty($this->reply_to)) {
725 $this->errors[] = $e->getMessage();
729 if (!empty($this->errors_to)) {
731 $headers->addMailboxHeader(
'Errors-To', $this->
getArrayAddress($this->errors_to));
733 $this->errors[] = $e->getMessage();
738 $this->message->setCharSet($conf->file->character_set_client);
740 $this->errors[] = $e->getMessage();
743 if (!empty($this->html)) {
752 if ($this->atleastoneimage) {
753 foreach ($this->html_images as $img) {
755 $attachment = Swift_Image::fromPath($img[
'fullpath']);
757 $imgcid = $this->message->embed($attachment);
759 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
761 foreach ($this->images_encoded as $img) {
763 $attachment = Swift_Image::fromPath($img[
'fullpath']);
765 $imgcid = $this->message->embed($attachment);
767 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
771 if ($this->msgishtml) {
772 $this->message->setBody($msg,
'text/html');
774 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
776 $this->message->setBody($msg,
'text/plain');
778 $this->message->addPart(
dol_nl2br($msg),
'text/html');
781 if (!empty($this->atleastonefile)) {
782 foreach ($filename_list as $i => $val) {
784 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
785 if (!empty($mimefilename_list[$i])) {
786 $attachment->setFilename($mimefilename_list[$i]);
788 $this->message->attach($attachment);
792 if (!empty($this->addr_cc)) {
796 $this->errors[] = $e->getMessage();
799 if (!empty($this->addr_bcc)) {
803 $this->errors[] = $e->getMessage();
807 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
809 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
811 $this->errors[] = $e->getMessage();
817 $this->error =
'Bad value for sendmode';
830 global $conf, $db, $langs, $hookmanager;
832 $errorlevel = error_reporting();
838 if (!is_object($hookmanager)) {
839 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
842 $hookmanager->initHooks(array(
'mail'));
844 $parameters = array();
846 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
848 $this->error =
"Error in hook maildao sendMail ".$reshook;
849 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
854 dol_syslog(
"A hook has replaced code to send email", LOG_DEBUG);
858 $sendingmode = $this->sendmode;
859 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
861 $listofmethods = array();
862 $listofmethods[
'mail'] =
'PHP mail function';
864 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
868 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
869 $linktoadminemailend =
'</a>';
870 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
871 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
872 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
873 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
875 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
876 $this->errors[] = $langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
879 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
885 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
887 $tmparray1 = explode(
',', $this->addr_to);
888 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
889 $this->error =
'Too much recipients in to:';
890 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
894 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
896 $tmparray2 = explode(
',', $this->addr_cc);
897 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
898 $this->error =
'Too much recipients in cc:';
899 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
903 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
905 $tmparray3 = explode(
',', $this->addr_bcc);
906 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
907 $this->error =
'Too much recipients in bcc:';
908 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
912 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
914 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
915 $this->error =
'Too much recipients in to:, cc:, bcc:';
916 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
920 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
921 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
922 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
923 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
924 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
925 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
926 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
927 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
928 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
929 if (!empty($this->sendcontext)) {
930 $smtpContextKey = strtoupper($this->sendcontext);
932 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
933 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
934 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
935 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
936 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
937 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
938 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
939 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
940 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
941 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
946 if ($this->sendmode ==
'mail') {
949 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_NOTICE);
954 if (isset($_SERVER[
"WINDIR"])) {
955 if (empty($this->addr_from)) {
956 $this->addr_from =
'robot@example.com';
958 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
971 if ($res && !$this->subject) {
972 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
973 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
977 if ($res && !$dest) {
978 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
979 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
984 $additionnalparam =
'';
991 $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) :
''));
994 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
998 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
1002 if (preg_match(
'/^win/i', PHP_OS)) {
1005 if (preg_match(
'/^mac/i', PHP_OS)) {
1009 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
1011 $this->message = stripslashes($this->message);
1018 $subjecttouse = $this->subject;
1023 if (!empty($additionnalparam)) {
1024 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
1026 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
1030 $langs->load(
"errors");
1031 $this->error =
"Failed to send mail with php mail";
1033 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
1035 $this->error .=
".<br>";
1036 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
1037 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1043 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1047 if (isset($_SERVER[
"WINDIR"])) {
1048 @ini_restore(
'sendmail_from');
1053 ini_restore(
'SMTP');
1056 ini_restore(
'smtp_port');
1058 } elseif ($this->sendmode ==
'smtps') {
1059 if (!is_object($this->smtps)) {
1060 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1061 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1067 $this->smtps->setTransportType(0);
1070 if (empty($conf->global->$keyforsmtpserver)) {
1071 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1073 if (empty($conf->global->$keyforsmtpport)) {
1074 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1086 $server = ($secure ? $secure.
'://' :
'').$server;
1090 $this->smtps->setHost($server);
1091 $this->smtps->setPort($port);
1097 $this->smtps->setID($loginid);
1101 $this->smtps->setPW($loginpass);
1105 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1110 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1111 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1113 $keyforprovider =
'';
1115 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1116 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1118 if (!empty($supportedoauth2array)) {
1119 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1120 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1121 $OAUTH_SERVICENAME = $nameofservice;
1123 $OAUTH_SERVICENAME =
'Unknown';
1126 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1128 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1130 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1132 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1136 if (is_object($tokenobj)) {
1137 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1140 if (is_object($tokenobj) && $expire) {
1141 $credentials =
new Credentials(
1146 $serviceFactory = new \OAuth\ServiceFactory();
1147 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1149 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1152 $refreshtoken = $tokenobj->getRefreshToken();
1154 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1156 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1157 $tokenobj->setRefreshToken($refreshtoken);
1158 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1161 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1164 if (is_object($tokenobj)) {
1165 $this->smtps->setToken($tokenobj->getAccessToken());
1167 $this->error =
"Token not found";
1171 $this->error = $e->getMessage();
1172 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1177 $from = $this->smtps->getFrom(
'org');
1178 if ($res && !$from) {
1179 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1180 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1183 $dest = $this->smtps->getTo();
1184 if ($res && !$dest) {
1185 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1186 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1194 $this->smtps->setDebug(
true);
1197 $result = $this->smtps->sendMsg();
1205 $smtperrorcode = $this->smtps->lastretval;
1206 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1208 if ($smtperrorcode ==
'421') {
1223 $result = $this->smtps->getErrors();
1224 if (empty($this->error) && empty($result)) {
1225 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1228 if (empty($this->error)) {
1229 $this->error = $result;
1231 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1239 } elseif ($this->sendmode ==
'swiftmailer') {
1242 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1245 if (empty($conf->global->$keyforsmtpserver)) {
1246 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1248 if (empty($conf->global->$keyforsmtpport)) {
1249 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1262 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalInt($keyforsmtpport), $secure);
1271 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1276 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1277 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1279 $keyforprovider =
'';
1281 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1282 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1284 if (!empty($supportedoauth2array)) {
1285 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1286 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1287 $OAUTH_SERVICENAME = $nameofservice;
1289 $OAUTH_SERVICENAME =
'Unknown';
1292 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1294 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1296 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1299 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1303 if (is_object($tokenobj)) {
1304 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1307 if (is_object($tokenobj) && $expire) {
1308 $credentials =
new Credentials(
1313 $serviceFactory = new \OAuth\ServiceFactory();
1314 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1316 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1317 $refreshtoken = $tokenobj->getRefreshToken();
1319 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1322 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1323 $tokenobj->setRefreshToken($refreshtoken);
1324 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1326 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1330 if (is_object($tokenobj)) {
1331 $this->transport->setAuthMode(
'XOAUTH2');
1332 $this->transport->setPassword($tokenobj->getAccessToken());
1334 $this->errors[] =
"Token not found";
1338 $this->errors[] = $e->getMessage();
1339 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1343 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1348 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1349 $this->message->setEncoder($contentEncoderBase64);
1352 $this->mailer =
new Swift_Mailer($this->transport);
1359 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1360 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1365 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1368 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1374 $failedRecipients = array();
1376 $result = $this->mailer->send($this->message, $failedRecipients);
1378 $this->errors[] = $e->getMessage();
1385 if (!empty($this->error) || !empty($this->errors) || !$result) {
1386 if (!empty($failedRecipients)) {
1387 $this->error =
'Transport failed for the following addresses: "' . implode(
'", "', $failedRecipients) .
'".';
1388 $this->errors[] = $this->error;
1390 dol_syslog(
"CMailFile::sendfile: mail end error=". implode(
' ', $this->errors), LOG_ERR);
1397 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1403 $this->error =
'Bad value for sendmode';
1416 $parameters = array(
'sent' => $res);
1418 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1420 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1421 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1426 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1427 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1430 error_reporting($errorlevel);