177 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 =
'')
179 global $conf, $dolibarr_main_data_root, $user;
181 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);
182 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
186 if (is_array($mimefilename_list)) {
187 foreach ($mimefilename_list as $key => $val) {
194 $this->sendcontext = $sendcontext;
197 $this->sendmode =
'';
198 if (!empty($this->sendcontext)) {
199 $smtpContextKey = strtoupper($this->sendcontext);
201 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
202 $this->sendmode = $smtpContextSendMode;
205 if (empty($this->sendmode)) {
206 $this->sendmode = (
getDolGlobalString(
'MAIN_MAIL_SENDMODE') ? $conf->global->MAIN_MAIL_SENDMODE :
'mail');
212 $this->eol2 =
"\r\n";
216 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
220 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
223 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"), 3);
226 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"), 3);
228 if (empty($subject)) {
229 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
230 $this->error =
'ErrorSubjectIsRequired';
234 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
239 if ($msgishtml == -1) {
240 $this->msgishtml = 0;
242 $this->msgishtml = 1;
245 $this->msgishtml = $msgishtml;
248 global $dolibarr_main_url_root;
251 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
252 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
256 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
259 $this->msgishtml = 1;
263 if ($this->msgishtml) {
272 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
274 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
275 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
284 if ($resultImageData < 0) {
285 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
286 dol_syslog(
"CMailFile::CMailfile: ".implode(
',', $this->errors));
287 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
290 $findimg += $resultImageData;
295 foreach ($this->html_images as $i => $val) {
296 if ($this->html_images[$i]) {
297 $this->atleastoneimage = 1;
298 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
299 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
301 $posindice = count($filename_list);
302 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
303 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
304 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
306 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
309 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
311 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
320 if (is_array($filename_list)) {
321 foreach ($filename_list as $i => $val) {
322 if ($filename_list[$i]) {
323 $this->atleastonefile = 1;
324 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);
333 foreach ($listofemailstoadd as $key => $val) {
334 $emailtoadd = $listofemailstoadd[$key];
335 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
336 if (!empty($user) && !empty($user->email)) {
337 $emailtoadd = $user->email;
342 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
346 $listofemailstoadd[$key] = $emailtoadd;
348 unset($listofemailstoadd[$key]);
351 if (!empty($listofemailstoadd)) {
352 $addr_bcc .= ($addr_bcc ?
', ' :
'').join(
', ', $listofemailstoadd);
357 if (empty($replyto)) {
365 $this->subject = $subject;
371 $this->deliveryreceipt = $deliveryreceipt;
374 $this->trackid = $trackid;
376 $this->filename_list = $filename_list;
377 $this->mimetype_list = $mimetype_list;
378 $this->mimefilename_list = $mimefilename_list;
379 $this->cid_list = $cid_list;
384 $this->addr_bcc =
'';
387 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
388 if (!empty($this->sendcontext)) {
389 $smtpContextKey = strtoupper($this->sendcontext);
391 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
392 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
396 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
400 if ($this->sendmode ==
'mail') {
411 if (!empty($moreinheader)) {
412 $smtp_headers .= $moreinheader;
418 if (!empty($this->html)) {
431 if (!empty($this->atleastonefile)) {
432 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
436 $this->headers = $smtp_headers.$mime_headers;
439 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
442 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
443 $this->message .= $text_body.$files_encoded;
444 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
445 } elseif ($this->sendmode ==
'smtps') {
449 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
450 $smtps =
new SMTPs();
451 $smtps->setCharSet($conf->file->character_set_client);
454 $subjecttouse = $this->subject;
459 $smtps->setSubject($subjecttouse);
462 $smtps->setTrackId($this->trackid);
465 if (!empty($moreinheader)) {
466 $smtps->setMoreInHeader($moreinheader);
469 if (!empty($this->html)) {
479 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
481 if ($this->msgishtml) {
482 $smtps->setBodyContent($msg,
'html');
484 $smtps->setBodyContent($msg,
'plain');
487 if ($this->atleastoneimage) {
488 foreach ($this->images_encoded as $img) {
489 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
493 if (!empty($this->atleastonefile)) {
494 foreach ($filename_list as $i => $val) {
495 $content = file_get_contents($filename_list[$i]);
496 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]);
500 $smtps->setCC($this->addr_cc);
501 $smtps->setBCC($this->addr_bcc);
502 $smtps->setErrorsTo($this->errors_to);
503 $smtps->setDeliveryReceipt($this->deliveryreceipt);
504 if (!empty($conf->global->$keyforsslseflsigned)) {
505 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
508 $host = dol_getprefix(
'email');
509 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
511 $this->smtps = $smtps;
512 } elseif ($this->sendmode ==
'swiftmailer') {
514 $host = dol_getprefix(
'email');
516 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
519 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
521 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
525 $this->message =
new Swift_Message();
528 $headers = $this->message->getHeaders();
530 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
531 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
532 $headerID = $this->msgid;
533 $msgid = $headers->get(
'Message-ID');
534 $msgid->setId($headerID);
541 $this->message->setSubject($this->subject);
543 $this->errors[] = $e->getMessage();
548 if (!empty($this->addr_from)) {
552 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
553 $adressEmailFrom = array();
554 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
555 $adressEmailFrom = reset($adressEmailFrom);
556 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
557 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
565 $this->errors[] = $e->getMessage();
570 if (!empty($this->addr_to)) {
574 $this->errors[] = $e->getMessage();
578 if (!empty($this->reply_to)) {
582 $this->errors[] = $e->getMessage();
586 if (!empty($this->errors_to)) {
588 $headers->addTextHeader(
'Errors-To', $this->
getValidAddress($this->errors_to, 0));
590 $this->errors[] = $e->getMessage();
595 $this->message->setCharSet($conf->file->character_set_client);
597 $this->errors[] = $e->getMessage();
600 if (!empty($this->html)) {
609 if ($this->atleastoneimage) {
610 foreach ($this->images_encoded as $img) {
612 $attachment = Swift_Image::fromPath($img[
'fullpath']);
614 $imgcid = $this->message->embed($attachment);
616 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
620 if ($this->msgishtml) {
621 $this->message->setBody($msg,
'text/html');
623 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
625 $this->message->setBody($msg,
'text/plain');
627 $this->message->addPart(
dol_nl2br($msg),
'text/html');
630 if (!empty($this->atleastonefile)) {
631 foreach ($filename_list as $i => $val) {
633 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
634 if (!empty($mimefilename_list[$i])) {
635 $attachment->setFilename($mimefilename_list[$i]);
637 $this->message->attach($attachment);
641 if (!empty($this->addr_cc)) {
645 $this->errors[] = $e->getMessage();
648 if (!empty($this->addr_bcc)) {
652 $this->errors[] = $e->getMessage();
655 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
657 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
659 $this->errors[] = $e->getMessage();
665 $this->error =
'Bad value for sendmode';
676 global $conf, $db, $langs, $hookmanager;
678 $errorlevel = error_reporting();
684 if (!is_object($hookmanager)) {
685 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
688 $hookmanager->initHooks(array(
'mail'));
690 $parameters = array();
692 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
694 $this->error =
"Error in hook maildao sendMail ".$reshook;
695 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
703 $sendingmode = $this->sendmode;
704 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
706 $listofmethods = array();
707 $listofmethods[
'mail'] =
'PHP mail function';
709 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
713 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
714 $linktoadminemailend =
'</a>';
715 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
716 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
717 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
718 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
720 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
721 $this->errors[] = $langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
724 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
730 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
732 $tmparray1 = explode(
',', $this->addr_to);
733 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
734 $this->error =
'Too much recipients in to:';
735 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
739 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
741 $tmparray2 = explode(
',', $this->addr_cc);
742 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
743 $this->error =
'Too much recipients in cc:';
744 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
748 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
750 $tmparray3 = explode(
',', $this->addr_bcc);
751 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
752 $this->error =
'Too much recipients in bcc:';
753 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
757 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
759 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
760 $this->error =
'Too much recipients in to:, cc:, bcc:';
761 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
765 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
766 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
767 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
768 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
769 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
770 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
771 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
772 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
773 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
774 if (!empty($this->sendcontext)) {
775 $smtpContextKey = strtoupper($this->sendcontext);
777 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
778 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
779 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
780 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
781 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
782 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
783 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
784 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
785 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
786 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
791 if ($this->sendmode ==
'mail') {
794 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
799 if (isset($_SERVER[
"WINDIR"])) {
800 if (empty($this->addr_from)) {
801 $this->addr_from =
'robot@example.com';
803 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
816 if ($res && !$this->subject) {
817 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
818 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
822 if ($res && !$dest) {
823 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
824 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
829 $additionnalparam =
'';
836 $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) :
''));
839 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
843 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
847 if (preg_match(
'/^win/i', PHP_OS)) {
850 if (preg_match(
'/^mac/i', PHP_OS)) {
854 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
856 $this->message = stripslashes($this->message);
863 $subjecttouse = $this->subject;
868 if (!empty($additionnalparam)) {
869 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
871 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
875 $langs->load(
"errors");
876 $this->error =
"Failed to send mail with php mail";
878 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
880 $this->error .=
".<br>";
881 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
882 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
888 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
892 if (isset($_SERVER[
"WINDIR"])) {
893 @ini_restore(
'sendmail_from');
901 ini_restore(
'smtp_port');
903 } elseif ($this->sendmode ==
'smtps') {
904 if (!is_object($this->smtps)) {
905 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
906 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
912 $this->smtps->setTransportType(0);
915 if (empty($conf->global->$keyforsmtpserver)) {
916 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
918 if (empty($conf->global->$keyforsmtpport)) {
919 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
925 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
928 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
931 $server = ($secure ? $secure.
'://' :
'').$server;
935 $this->smtps->setHost($server);
936 $this->smtps->setPort($port);
940 if (!empty($conf->global->$keyforsmtpid)) {
941 $loginid = $conf->global->$keyforsmtpid;
942 $this->smtps->setID($loginid);
944 if (!empty($conf->global->$keyforsmtppw)) {
945 $loginpass = $conf->global->$keyforsmtppw;
946 $this->smtps->setPW($loginpass);
950 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
955 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
956 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
958 $keyforprovider =
'';
960 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
961 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
963 if (!empty($supportedoauth2array)) {
964 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
966 $OAUTH_SERVICENAME =
'Unknown';
969 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
971 $storage =
new DoliStorage($db, $conf, $keyforprovider);
973 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
976 if (is_object($tokenobj)) {
977 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
980 if (is_object($tokenobj) && $expire) {
981 $credentials =
new Credentials(
986 $serviceFactory = new \OAuth\ServiceFactory();
987 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
989 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
991 $refreshtoken = $tokenobj->getRefreshToken();
992 $tokenobj = $apiService->refreshAccessToken($tokenobj);
993 $tokenobj->setRefreshToken($refreshtoken);
994 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
997 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
998 if (is_object($tokenobj)) {
999 $this->smtps->setToken($tokenobj->getAccessToken());
1001 $this->error =
"Token not found";
1005 $this->error = $e->getMessage();
1006 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1011 $from = $this->smtps->getFrom(
'org');
1012 if ($res && !$from) {
1013 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1014 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1017 $dest = $this->smtps->getTo();
1018 if ($res && !$dest) {
1019 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1020 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1028 $this->smtps->setDebug(
true);
1031 $result = $this->smtps->sendMsg();
1039 $smtperrorcode = $this->smtps->lastretval;
1040 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1042 if ($smtperrorcode ==
'421') {
1057 $result = $this->smtps->getErrors();
1058 if (empty($this->error) && empty($result)) {
1059 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1062 if (empty($this->error)) {
1063 $this->error = $result;
1065 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1073 } elseif ($this->sendmode ==
'swiftmailer') {
1076 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1079 if (empty($conf->global->$keyforsmtpserver)) {
1080 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1082 if (empty($conf->global->$keyforsmtpport)) {
1083 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1089 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1092 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1096 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalString($keyforsmtpport), $secure);
1098 if (!empty($conf->global->$keyforsmtpid)) {
1099 $this->transport->setUsername($conf->global->$keyforsmtpid);
1101 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1102 $this->transport->setPassword($conf->global->$keyforsmtppw);
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 $OAUTH_SERVICENAME =
'Unknown';
1119 if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array)
1120 && array_key_exists(
'name', $supportedoauth2array[$keyforsupportedoauth2array])
1121 && !empty($supportedoauth2array[$keyforsupportedoauth2array][
'name'])) {
1122 $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array][
'name'].(!empty($keyforprovider) ?
'-'.$keyforprovider :
'');
1125 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1127 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1130 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1133 if (is_object($tokenobj)) {
1134 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1137 if (is_object($tokenobj) && $expire) {
1138 $credentials =
new Credentials(
1143 $serviceFactory = new \OAuth\ServiceFactory();
1144 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1146 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1148 $refreshtoken = $tokenobj->getRefreshToken();
1149 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1150 $tokenobj->setRefreshToken($refreshtoken);
1151 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1153 if (is_object($tokenobj)) {
1154 $this->transport->setAuthMode(
'XOAUTH2');
1155 $this->transport->setPassword($tokenobj->getAccessToken());
1157 $this->errors[] =
"Token not found";
1161 $this->errors[] = $e->getMessage();
1162 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1166 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1171 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1172 $this->message->setEncoder($contentEncoderBase64);
1175 $this->mailer =
new Swift_Mailer($this->transport);
1179 $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
1180 $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
1181 $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
1182 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1183 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1188 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1191 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1197 $failedRecipients = array();
1199 $result = $this->mailer->send($this->message, $failedRecipients);
1201 $this->errors[] = $e->getMessage();
1208 if (!empty($this->error) || !empty($this->errors) || !$result) {
1209 if (!empty($failedRecipients)) {
1210 $this->error =
'Transport failed for the following addresses: "' . join(
'", "', $failedRecipients) .
'".';
1211 $this->errors[] = $this->error;
1213 dol_syslog(
"CMailFile::sendfile: mail end error=". join(
' ', $this->errors), LOG_ERR);
1220 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1226 return 'Bad value for sendmode';
1230 foreach ($this->html_images as $val) {
1231 if (!empty($val[
'type']) && $val[
'type'] ==
'cidfromdata') {
1236 $parameters = array(
'sent' => $res);
1238 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1240 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1241 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1246 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1247 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1250 error_reporting($errorlevel);