229 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 =
'')
231 global
$conf, $dolibarr_main_data_root, $user;
233 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");
234 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;
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 $dolibarr_main_data_root_images = $dolibarr_main_data_root;
334 if ((
int)
$conf->entity !== 1) {
335 $dolibarr_main_data_root_images .=
'/'.$conf->entity.
'/';
337 $findimg = $this->
findHtmlImages($dolibarr_main_data_root_images.
'/medias');
339 dol_syslog(
"CMailFile::CMailFile: Error on findHtmlImages");
340 $this->error =
'ErrorInAddAttachmentsImageBaseOnMedia';
350 if ($resultImageData < 0) {
351 dol_syslog(
"CMailFile::CMailFile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
352 $this->error =
'ErrorInAddAttachmentsImageBaseIsSrcData';
355 $findimg += $resultImageData;
360 foreach ($this->html_images as $i => $val) {
361 if ($this->html_images[$i]) {
362 $this->atleastoneimage = 1;
363 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
364 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
366 $posindice = count($filename_list);
367 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
368 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
369 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
371 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
374 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
376 dol_syslog(
"CMailFile::CMailFile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
385 if (is_array($filename_list)) {
386 foreach ($filename_list as $i => $val) {
387 if ($filename_list[$i]) {
388 $this->atleastonefile = 1;
389 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);
398 foreach ($listofemailstoadd as $key => $val) {
399 $emailtoadd = $listofemailstoadd[$key];
400 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
401 if (!empty($user) && !empty($user->email)) {
402 $emailtoadd = $user->email;
407 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
411 $listofemailstoadd[$key] = $emailtoadd;
413 unset($listofemailstoadd[$key]);
416 if (!empty($listofemailstoadd)) {
417 $addr_bcc .= ($addr_bcc ?
', ' :
'').implode(
', ', $listofemailstoadd);
424 $listofemailstonotsendto = explode(
',',
getDolGlobalString(
'MAIN_MAIL_FORCE_NOT_SENDING_TO'));
428 $tabto = explode(
",", $to);
429 foreach ($tabto as $key => $addrto) {
431 if (in_array($addrto[0], $listofemailstonotsendto)) {
439 $to = implode(
',', $tabto);
443 $tabcc = explode(
',', $addr_cc);
444 foreach ($tabcc as $key => $cc) {
446 if (in_array($cc[0], $listofemailstonotsendto)) {
454 $addr_cc = implode(
',', $tabcc);
458 $tabbcc = explode(
',', $addr_bcc);
459 foreach ($tabbcc as $key => $bcc) {
461 if (in_array($bcc[0], $listofemailstonotsendto)) {
462 unset($tabbcc[$key]);
469 $addr_bcc = implode(
',', $tabbcc);
473 if (empty($replyto)) {
481 $this->subject = $subject;
487 $this->deliveryreceipt = $deliveryreceipt;
490 $this->trackid = $trackid;
491 $this->in_reply_to = $in_reply_to;
492 $this->references = $references;
494 $this->filename_list = $filename_list;
495 $this->mimetype_list = $mimetype_list;
496 $this->mimefilename_list = $mimefilename_list;
497 $this->cid_list = $cid_list;
502 $this->addr_bcc =
'';
505 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
506 if (!empty($this->sendcontext)) {
507 $smtpContextKey = strtoupper($this->sendcontext);
509 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
510 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
514 dol_syslog(
"CMailFile::CMailFile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
518 if ($this->sendmode ==
'mail') {
529 if (!empty($moreinheader)) {
530 $smtp_headers .= $moreinheader;
536 if (!empty($this->html)) {
549 if (!empty($this->atleastonefile) && $filename_list !==
null && $mimetype_list !==
null && $mimefilename_list !==
null) {
550 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
554 $this->headers = $smtp_headers.$mime_headers;
557 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
560 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
561 $this->message .= $text_body.$files_encoded;
562 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
563 } elseif ($this->sendmode ==
'smtps') {
566 $host = dol_getprefix(
'email');
568 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
569 $smtps =
new SMTPs();
570 $smtps->setCharSet(
$conf->file->character_set_client);
573 $subjecttouse = $this->subject;
578 $smtps->setSubject($subjecttouse);
583 $smtps->setTrackId($this->trackid);
585 if (!empty($this->in_reply_to)) {
586 $smtps->setInReplyTo($this->in_reply_to);
588 if (!empty($this->references)) {
589 $smtps->setReferences($this->references);
592 if (!empty($moreinheader)) {
593 $smtps->setMoreInHeader($moreinheader);
598 if (!empty($this->html)) {
611 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
613 if ($this->msgishtml) {
614 $smtps->setBodyContent($msg,
'html');
616 $smtps->setBodyContent($msg,
'plain');
619 if (!empty($this->atleastoneimage)) {
620 foreach ($this->images_encoded as $img) {
621 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
625 if (!empty($this->atleastonefile)) {
626 foreach ($filename_list as $i => $val) {
627 $content = file_get_contents($filename_list[$i]);
628 if (empty($cid_list[$i])) {
629 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], (empty($cid_list[$i]) ?
'' : $cid_list[$i]));
634 $smtps->setCC($this->addr_cc);
635 $smtps->setBCC($this->addr_bcc);
636 $smtps->setErrorsTo($this->errors_to);
637 $smtps->setDeliveryReceipt($this->deliveryreceipt);
641 $options = array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true));
644 $options = array_merge($options, array(
'ssl' => array(
'capture_peer_cert' =>
true,
'capture_peer_cert_chain' =>
true)));
654 $options = array_merge($options, array(
'socket' => [
'bindto' =>
'0.0.0.0:0']));
656 if (!empty($options)) {
657 $smtps->setOptions($options);
660 $this->msgid = uniqid(
'',
true).
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
662 $smtps->setMessageID($this->msgid);
664 $this->smtps = $smtps;
665 } elseif ($this->sendmode ==
'swiftmailer') {
668 $host = dol_getprefix(
'email');
670 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
673 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
675 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
679 $this->message =
new Swift_Message();
682 $headers = $this->message->getHeaders();
684 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
685 $this->msgid = uniqid(
'',
true).
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
686 $headerID = $this->msgid;
687 $msgid = $headers->get(
'Message-ID');
688 if ($msgid instanceof Swift_Mime_Headers_IdentificationHeader) {
689 $msgid->setId($headerID);
693 if (!empty($this->in_reply_to)) {
694 $headers->addIdHeader(
'In-Reply-To', $this->in_reply_to);
697 if (!empty($this->references)) {
698 $headers->addIdHeader(
'References', $this->references);
701 if (!empty($moreinheader)) {
702 $moreinheaderarray = preg_split(
'/[\r\n]+/', $moreinheader);
703 foreach ($moreinheaderarray as $moreinheaderval) {
704 $moreinheadervaltmp = explode(
':', $moreinheaderval, 2);
705 if (!empty($moreinheadervaltmp[0]) && !empty($moreinheadervaltmp[1])) {
706 $headers->addTextHeader($moreinheadervaltmp[0], $moreinheadervaltmp[1]);
713 $this->message->setSubject($this->subject);
715 $this->errors[] = $e->getMessage();
720 if (!empty($this->addr_from)) {
724 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
725 $adressEmailFrom = array();
726 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
727 $adressEmailFrom = reset($adressEmailFrom);
728 if ($emailMatchs !==
false && filter_var(
getDolGlobalString(
'MAIN_MAIL_SMTPS_ID'), FILTER_VALIDATE_EMAIL) &&
getDolGlobalString(
'MAIN_MAIL_SMTPS_ID') !== $adressEmailFrom[0]) {
737 $this->errors[] = $e->getMessage();
742 if (!empty($this->addr_to)) {
746 $this->errors[] = $e->getMessage();
750 if (!empty($this->reply_to)) {
754 $this->errors[] = $e->getMessage();
758 if (!empty($this->errors_to)) {
760 $headers->addMailboxHeader(
'Errors-To', $this->
getArrayAddress($this->errors_to));
762 $this->errors[] = $e->getMessage();
767 $this->message->setCharSet(
$conf->file->character_set_client);
769 $this->errors[] = $e->getMessage();
772 if (!empty($this->html)) {
781 if ($this->atleastoneimage) {
782 foreach ($this->html_images as $img) {
784 $attachment = Swift_Image::fromPath($img[
'fullpath']);
786 $imgcid = $this->message->embed($attachment);
788 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
790 foreach ($this->images_encoded as $img) {
792 $attachment = Swift_Image::fromPath($img[
'fullpath']);
794 $imgcid = $this->message->embed($attachment);
796 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
800 if ($this->msgishtml) {
801 $this->message->setBody($msg,
'text/html');
803 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
805 $this->message->setBody($msg,
'text/plain');
807 $this->message->addPart(
dol_nl2br($msg),
'text/html');
810 if (!empty($this->atleastonefile)) {
811 foreach ($filename_list as $i => $val) {
813 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
814 if (!empty($mimefilename_list[$i])) {
815 $attachment->setFilename($mimefilename_list[$i]);
817 $this->message->attach($attachment);
821 if (!empty($this->addr_cc)) {
825 $this->errors[] = $e->getMessage();
828 if (!empty($this->addr_bcc)) {
832 $this->errors[] = $e->getMessage();
835 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
837 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
839 $this->errors[] = $e->getMessage();
845 $this->error =
'Bad value for sendmode';
858 global
$conf,
$db, $langs, $hookmanager;
860 $errorlevel = error_reporting();
866 if (!is_object($hookmanager)) {
867 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
870 $hookmanager->initHooks(array(
'mail'));
872 $parameters = array();
874 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
876 $this->error =
"Error in hook maildao sendMail ".$reshook;
877 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
882 dol_syslog(
"A hook has replaced code to send email", LOG_DEBUG);
886 $sendingmode = $this->sendmode;
887 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
889 $listofmethods = array();
890 $listofmethods[
'mail'] =
'PHP mail function';
892 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
896 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
897 $linktoadminemailend =
'</a>';
898 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
899 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
900 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
901 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
903 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
904 $this->errors[] = $langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
907 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
913 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
915 $tmparray1 = explode(
',', $this->addr_to);
916 if (count($tmparray1) >
$conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
917 $this->error =
'Too much recipients in to:';
918 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
922 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
924 $tmparray2 = explode(
',', $this->addr_cc);
925 if (count($tmparray2) >
$conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
926 $this->error =
'Too much recipients in cc:';
927 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
931 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
933 $tmparray3 = explode(
',', $this->addr_bcc);
934 if (count($tmparray3) >
$conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
935 $this->error =
'Too much recipients in bcc:';
936 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
940 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
942 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) >
$conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
943 $this->error =
'Too much recipients in to:, cc:, bcc:';
944 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
948 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
949 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
950 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
951 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
952 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
953 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
954 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
955 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
956 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
957 if (!empty($this->sendcontext)) {
958 $smtpContextKey = strtoupper($this->sendcontext);
960 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
961 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
962 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
963 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
964 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
965 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
966 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
967 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
968 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
969 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
974 if ($this->sendmode ==
'mail') {
977 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_NOTICE);
982 if (isset($_SERVER[
"WINDIR"])) {
983 if (empty($this->addr_from)) {
984 $this->addr_from =
'robot@example.com';
986 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
999 if ($res && !$this->subject) {
1000 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
1001 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1005 if ($res && !$dest) {
1006 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
1007 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1012 $additionnalparam =
'';
1019 $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) :
''));
1022 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
1026 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
1030 if (preg_match(
'/^win/i', PHP_OS)) {
1033 if (preg_match(
'/^mac/i', PHP_OS)) {
1037 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
1039 $this->message = stripslashes($this->message);
1046 $subjecttouse = $this->subject;
1051 if (!empty($additionnalparam)) {
1052 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
1054 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
1058 $langs->load(
"errors");
1059 $this->error =
"Failed to send mail with php mail";
1061 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
1063 $this->error .=
".<br>";
1064 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
1065 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1071 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1075 if (isset($_SERVER[
"WINDIR"])) {
1076 @ini_restore(
'sendmail_from');
1081 ini_restore(
'SMTP');
1084 ini_restore(
'smtp_port');
1086 } elseif ($this->sendmode ==
'smtps') {
1087 if (!is_object($this->smtps)) {
1088 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1089 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1095 $this->smtps->setTransportType(0);
1098 if (empty(
$conf->global->$keyforsmtpserver)) {
1099 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1101 if (empty(
$conf->global->$keyforsmtpport)) {
1102 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1114 $server = ($secure ? $secure.
'://' :
'').$server;
1118 $this->smtps->setHost($server);
1119 $this->smtps->setPort($port);
1125 $this->smtps->setID($loginid);
1129 $this->smtps->setPW($loginpass);
1133 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1138 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1139 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1141 $keyforprovider =
'';
1143 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1144 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1146 if (!empty($supportedoauth2array)) {
1147 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1148 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1149 $OAUTH_SERVICENAME = $nameofservice;
1151 $OAUTH_SERVICENAME =
'Unknown';
1154 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1156 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1160 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1164 if (is_object($tokenobj)) {
1165 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1168 if (is_object($tokenobj) && $expire) {
1169 $credentials =
new Credentials(
1174 $serviceFactory = new \OAuth\ServiceFactory();
1175 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
1176 $serviceFactory->setHttpClient($httpClient);
1177 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1180 $oauthScopes = array();
1182 if (!empty($oauthScopesStr)) {
1183 $oauthScopes = preg_split(
'/\s*,\s*/', $oauthScopesStr);
1184 if (!is_array($oauthScopes)) {
1185 $oauthScopes = array();
1190 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $oauthScopes);
1194 $refreshtoken = $tokenobj->getRefreshToken();
1196 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1198 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1199 if (empty($tokenobj->getRefreshToken())) {
1200 $tokenobj->setRefreshToken($refreshtoken);
1202 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1205 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1208 if (is_object($tokenobj)) {
1209 $this->smtps->setToken($tokenobj->getAccessToken());
1211 $this->error =
"Token not found";
1215 $this->error = $e->getMessage();
1216 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1221 $from = $this->smtps->getFrom(
'org');
1222 if ($res && !$from) {
1223 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1224 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1227 $dest = $this->smtps->getTo();
1228 if ($res && !$dest) {
1229 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1230 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1238 $this->smtps->setDebug(
true);
1241 $result = $this->smtps->sendMsg();
1249 $smtperrorcode = $this->smtps->lastretval;
1250 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1252 if ($smtperrorcode ==
'421') {
1266 dol_syslog(
"CMailFile::sendfile: mail SMTP sendMsg is success", LOG_DEBUG);
1269 $result = $this->smtps->getErrors();
1271 if (empty($this->error) && empty($result)) {
1272 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1275 if (empty($this->error)) {
1276 $this->error = $result;
1278 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1282 $this->
save_dump_mail_in_err(
'Mail smtp error '.$smtperrorcode.
' with topic '.$this->subject.
' - '.$this->error);
1286 } elseif ($this->sendmode ==
'swiftmailer') {
1289 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1292 if (empty(
$conf->global->$keyforsmtpserver)) {
1293 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1295 if (empty(
$conf->global->$keyforsmtpport)) {
1296 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1309 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalInt($keyforsmtpport), $secure);
1318 $this->transport->setAuthMode(
'XOAUTH2');
1319 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1324 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1325 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1327 $keyforprovider =
'';
1329 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1330 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1332 if (!empty($supportedoauth2array)) {
1333 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1334 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1335 $OAUTH_SERVICENAME = $nameofservice;
1337 $OAUTH_SERVICENAME =
'Unknown';
1340 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1342 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1347 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1351 if (is_object($tokenobj)) {
1352 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1355 if (is_object($tokenobj) && $expire) {
1356 $credentials =
new Credentials(
1361 $serviceFactory = new \OAuth\ServiceFactory();
1362 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
1363 $serviceFactory->setHttpClient($httpClient);
1364 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1367 $oauthScopes = array();
1369 if (!empty($oauthScopesStr)) {
1370 $oauthScopes = preg_split(
'/\s*,\s*/', $oauthScopesStr);
1371 if (!is_array($oauthScopes)) {
1372 $oauthScopes = array();
1377 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $oauthScopes);
1378 $refreshtoken = $tokenobj->getRefreshToken();
1380 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1382 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1383 if (empty($tokenobj->getRefreshToken())) {
1384 $tokenobj->setRefreshToken($refreshtoken);
1386 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1388 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1392 if (is_object($tokenobj)) {
1393 $this->transport->setAuthMode(
'XOAUTH2');
1394 $this->transport->setPassword($tokenobj->getAccessToken());
1396 $this->errors[] =
"Token not found";
1397 dol_syslog(
"CMailFile::sendfile: OAuth2 token object is not valid", LOG_ERR);
1401 $this->errors[] = $e->getMessage();
1402 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1406 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1411 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1412 $this->message->setEncoder($contentEncoderBase64);
1415 $this->mailer =
new Swift_Mailer($this->transport);
1422 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1423 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1428 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1431 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1437 $failedRecipients = array();
1439 $result = $this->mailer->send($this->message, $failedRecipients);
1441 $this->errors[] = $e->getMessage();
1448 if (!empty($this->error) || !empty($this->errors) || !$result) {
1449 if (!empty($failedRecipients)) {
1450 $this->error =
'Transport failed for the following addresses: "' . implode(
'", "', $failedRecipients) .
'".';
1451 $this->errors[] = $this->error;
1453 dol_syslog(
"CMailFile::sendfile: mail end error=". implode(
' ', $this->errors), LOG_ERR);
1460 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1466 $this->error =
'Bad value for sendmode';
1479 $parameters = array(
'sent' => $res);
1481 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1483 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1484 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1489 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1490 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1493 error_reporting($errorlevel);