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->
getArrayAddress($this->errors_to));
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();
656 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
658 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
660 $this->errors[] = $e->getMessage();
666 $this->error =
'Bad value for sendmode';
677 global $conf, $db, $langs, $hookmanager;
679 $errorlevel = error_reporting();
685 if (!is_object($hookmanager)) {
686 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
689 $hookmanager->initHooks(array(
'mail'));
691 $parameters = array();
693 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
695 $this->error =
"Error in hook maildao sendMail ".$reshook;
696 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
704 $sendingmode = $this->sendmode;
705 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
707 $listofmethods = array();
708 $listofmethods[
'mail'] =
'PHP mail function';
710 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
714 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
715 $linktoadminemailend =
'</a>';
716 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
717 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
718 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
719 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
721 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
722 $this->errors[] = $langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
725 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
731 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
733 $tmparray1 = explode(
',', $this->addr_to);
734 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
735 $this->error =
'Too much recipients in to:';
736 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
740 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
742 $tmparray2 = explode(
',', $this->addr_cc);
743 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
744 $this->error =
'Too much recipients in cc:';
745 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
749 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
751 $tmparray3 = explode(
',', $this->addr_bcc);
752 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
753 $this->error =
'Too much recipients in bcc:';
754 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
758 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
760 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
761 $this->error =
'Too much recipients in to:, cc:, bcc:';
762 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
766 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
767 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
768 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
769 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
770 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
771 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
772 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
773 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
774 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
775 if (!empty($this->sendcontext)) {
776 $smtpContextKey = strtoupper($this->sendcontext);
778 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
779 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
780 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
781 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
782 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
783 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
784 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
785 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
786 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
787 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
792 if ($this->sendmode ==
'mail') {
795 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
800 if (isset($_SERVER[
"WINDIR"])) {
801 if (empty($this->addr_from)) {
802 $this->addr_from =
'robot@example.com';
804 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
817 if ($res && !$this->subject) {
818 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
819 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
823 if ($res && !$dest) {
824 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
825 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
830 $additionnalparam =
'';
837 $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) :
''));
840 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
844 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
848 if (preg_match(
'/^win/i', PHP_OS)) {
851 if (preg_match(
'/^mac/i', PHP_OS)) {
855 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
857 $this->message = stripslashes($this->message);
864 $subjecttouse = $this->subject;
869 if (!empty($additionnalparam)) {
870 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
872 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
876 $langs->load(
"errors");
877 $this->error =
"Failed to send mail with php mail";
879 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
881 $this->error .=
".<br>";
882 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
883 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
889 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
893 if (isset($_SERVER[
"WINDIR"])) {
894 @ini_restore(
'sendmail_from');
902 ini_restore(
'smtp_port');
904 } elseif ($this->sendmode ==
'smtps') {
905 if (!is_object($this->smtps)) {
906 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
907 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
913 $this->smtps->setTransportType(0);
916 if (empty($conf->global->$keyforsmtpserver)) {
917 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
919 if (empty($conf->global->$keyforsmtpport)) {
920 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
926 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
929 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
932 $server = ($secure ? $secure.
'://' :
'').$server;
936 $this->smtps->setHost($server);
937 $this->smtps->setPort($port);
941 if (!empty($conf->global->$keyforsmtpid)) {
942 $loginid = $conf->global->$keyforsmtpid;
943 $this->smtps->setID($loginid);
945 if (!empty($conf->global->$keyforsmtppw)) {
946 $loginpass = $conf->global->$keyforsmtppw;
947 $this->smtps->setPW($loginpass);
951 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
956 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
957 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
959 $keyforprovider =
'';
961 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
962 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
964 if (!empty($supportedoauth2array)) {
965 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
967 $OAUTH_SERVICENAME =
'Unknown';
970 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
972 $storage =
new DoliStorage($db, $conf, $keyforprovider);
974 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
977 if (is_object($tokenobj)) {
978 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
981 if (is_object($tokenobj) && $expire) {
982 $credentials =
new Credentials(
987 $serviceFactory = new \OAuth\ServiceFactory();
988 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
990 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
992 $refreshtoken = $tokenobj->getRefreshToken();
993 $tokenobj = $apiService->refreshAccessToken($tokenobj);
994 $tokenobj->setRefreshToken($refreshtoken);
995 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
998 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
999 if (is_object($tokenobj)) {
1000 $this->smtps->setToken($tokenobj->getAccessToken());
1002 $this->error =
"Token not found";
1006 $this->error = $e->getMessage();
1007 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1012 $from = $this->smtps->getFrom(
'org');
1013 if ($res && !$from) {
1014 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1015 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1018 $dest = $this->smtps->getTo();
1019 if ($res && !$dest) {
1020 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1021 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1029 $this->smtps->setDebug(
true);
1032 $result = $this->smtps->sendMsg();
1040 $smtperrorcode = $this->smtps->lastretval;
1041 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1043 if ($smtperrorcode ==
'421') {
1058 $result = $this->smtps->getErrors();
1059 if (empty($this->error) && empty($result)) {
1060 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1063 if (empty($this->error)) {
1064 $this->error = $result;
1066 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1074 } elseif ($this->sendmode ==
'swiftmailer') {
1077 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1080 if (empty($conf->global->$keyforsmtpserver)) {
1081 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1083 if (empty($conf->global->$keyforsmtpport)) {
1084 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1090 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1093 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1097 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalString($keyforsmtpport), $secure);
1099 if (!empty($conf->global->$keyforsmtpid)) {
1100 $this->transport->setUsername($conf->global->$keyforsmtpid);
1102 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1103 $this->transport->setPassword($conf->global->$keyforsmtppw);
1106 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1111 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1112 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1114 $keyforprovider =
'';
1116 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1117 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1119 $OAUTH_SERVICENAME =
'Unknown';
1120 if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array)
1121 && array_key_exists(
'name', $supportedoauth2array[$keyforsupportedoauth2array])
1122 && !empty($supportedoauth2array[$keyforsupportedoauth2array][
'name'])) {
1123 $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array][
'name'].(!empty($keyforprovider) ?
'-'.$keyforprovider :
'');
1126 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1128 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1131 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1134 if (is_object($tokenobj)) {
1135 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1138 if (is_object($tokenobj) && $expire) {
1139 $credentials =
new Credentials(
1144 $serviceFactory = new \OAuth\ServiceFactory();
1145 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1147 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1149 $refreshtoken = $tokenobj->getRefreshToken();
1150 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1151 $tokenobj->setRefreshToken($refreshtoken);
1152 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1154 if (is_object($tokenobj)) {
1155 $this->transport->setAuthMode(
'XOAUTH2');
1156 $this->transport->setPassword($tokenobj->getAccessToken());
1158 $this->errors[] =
"Token not found";
1162 $this->errors[] = $e->getMessage();
1163 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1167 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1172 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1173 $this->message->setEncoder($contentEncoderBase64);
1176 $this->mailer =
new Swift_Mailer($this->transport);
1180 $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
1181 $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
1182 $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
1183 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1184 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1189 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1192 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1198 $failedRecipients = array();
1200 $result = $this->mailer->send($this->message, $failedRecipients);
1202 $this->errors[] = $e->getMessage();
1209 if (!empty($this->error) || !empty($this->errors) || !$result) {
1210 if (!empty($failedRecipients)) {
1211 $this->error =
'Transport failed for the following addresses: "' . join(
'", "', $failedRecipients) .
'".';
1212 $this->errors[] = $this->error;
1214 dol_syslog(
"CMailFile::sendfile: mail end error=". join(
' ', $this->errors), LOG_ERR);
1221 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1227 return 'Bad value for sendmode';
1231 foreach ($this->html_images as $val) {
1232 if (!empty($val[
'type']) && $val[
'type'] ==
'cidfromdata') {
1237 $parameters = array(
'sent' => $res);
1239 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1241 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1242 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1247 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1248 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1251 error_reporting($errorlevel);