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 $dolibarr_main_data_root_images=$dolibarr_main_data_root;
273 if ((
int) $conf->entity !== 1) {
274 $dolibarr_main_data_root_images.=
'/'.$conf->entity.
'/';
276 $findimg = $this->
findHtmlImages($dolibarr_main_data_root_images.
'/medias');
278 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
279 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
288 if ($resultImageData < 0) {
289 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
290 dol_syslog(
"CMailFile::CMailfile: ".implode(
',', $this->errors));
291 $this->error =
'ErrorInAddAttachementsImageBaseOnMedia';
294 $findimg += $resultImageData;
299 foreach ($this->html_images as $i => $val) {
300 if ($this->html_images[$i]) {
301 $this->atleastoneimage = 1;
302 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
303 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
305 $posindice = count($filename_list);
306 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
307 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
308 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
310 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
313 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
315 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
324 if (is_array($filename_list)) {
325 foreach ($filename_list as $i => $val) {
326 if ($filename_list[$i]) {
327 $this->atleastonefile = 1;
328 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);
337 foreach ($listofemailstoadd as $key => $val) {
338 $emailtoadd = $listofemailstoadd[$key];
339 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
340 if (!empty($user) && !empty($user->email)) {
341 $emailtoadd = $user->email;
346 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
350 $listofemailstoadd[$key] = $emailtoadd;
352 unset($listofemailstoadd[$key]);
355 if (!empty($listofemailstoadd)) {
356 $addr_bcc .= ($addr_bcc ?
', ' :
'').join(
', ', $listofemailstoadd);
361 if (empty($replyto)) {
369 $this->subject = $subject;
375 $this->deliveryreceipt = $deliveryreceipt;
378 $this->trackid = $trackid;
380 $this->filename_list = $filename_list;
381 $this->mimetype_list = $mimetype_list;
382 $this->mimefilename_list = $mimefilename_list;
383 $this->cid_list = $cid_list;
388 $this->addr_bcc =
'';
391 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
392 if (!empty($this->sendcontext)) {
393 $smtpContextKey = strtoupper($this->sendcontext);
395 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
396 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
400 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
404 if ($this->sendmode ==
'mail') {
415 if (!empty($moreinheader)) {
416 $smtp_headers .= $moreinheader;
422 if (!empty($this->html)) {
435 if (!empty($this->atleastonefile)) {
436 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
440 $this->headers = $smtp_headers.$mime_headers;
443 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
446 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
447 $this->message .= $text_body.$files_encoded;
448 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
449 } elseif ($this->sendmode ==
'smtps') {
453 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
454 $smtps =
new SMTPs();
455 $smtps->setCharSet($conf->file->character_set_client);
458 $subjecttouse = $this->subject;
463 $smtps->setSubject($subjecttouse);
466 $smtps->setTrackId($this->trackid);
469 if (!empty($moreinheader)) {
470 $smtps->setMoreInHeader($moreinheader);
473 if (!empty($this->html)) {
483 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
485 if ($this->msgishtml) {
486 $smtps->setBodyContent($msg,
'html');
488 $smtps->setBodyContent($msg,
'plain');
491 if ($this->atleastoneimage) {
492 foreach ($this->images_encoded as $img) {
493 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
497 if (!empty($this->atleastonefile)) {
498 foreach ($filename_list as $i => $val) {
499 $content = file_get_contents($filename_list[$i]);
500 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]);
504 $smtps->setCC($this->addr_cc);
505 $smtps->setBCC($this->addr_bcc);
506 $smtps->setErrorsTo($this->errors_to);
507 $smtps->setDeliveryReceipt($this->deliveryreceipt);
508 if (!empty($conf->global->$keyforsslseflsigned)) {
509 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
512 $host = dol_getprefix(
'email');
513 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
515 $this->smtps = $smtps;
516 } elseif ($this->sendmode ==
'swiftmailer') {
518 $host = dol_getprefix(
'email');
520 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
523 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
525 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
529 $this->message =
new Swift_Message();
532 $headers = $this->message->getHeaders();
534 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
535 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
536 $headerID = $this->msgid;
537 $msgid = $headers->get(
'Message-ID');
538 $msgid->setId($headerID);
545 $this->message->setSubject($this->subject);
547 $this->errors[] = $e->getMessage();
552 if (!empty($this->addr_from)) {
556 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
557 $adressEmailFrom = array();
558 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
559 $adressEmailFrom = reset($adressEmailFrom);
560 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
561 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
569 $this->errors[] = $e->getMessage();
574 if (!empty($this->addr_to)) {
578 $this->errors[] = $e->getMessage();
582 if (!empty($this->reply_to)) {
586 $this->errors[] = $e->getMessage();
590 if (!empty($this->errors_to)) {
592 $headers->addTextHeader(
'Errors-To', $this->
getValidAddress($this->errors_to, 0));
594 $this->errors[] = $e->getMessage();
599 $this->message->setCharSet($conf->file->character_set_client);
601 $this->errors[] = $e->getMessage();
604 if (!empty($this->html)) {
613 if ($this->atleastoneimage) {
614 foreach ($this->images_encoded as $img) {
616 $attachment = Swift_Image::fromPath($img[
'fullpath']);
618 $imgcid = $this->message->embed($attachment);
620 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
624 if ($this->msgishtml) {
625 $this->message->setBody($msg,
'text/html');
627 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
629 $this->message->setBody($msg,
'text/plain');
631 $this->message->addPart(
dol_nl2br($msg),
'text/html');
634 if (!empty($this->atleastonefile)) {
635 foreach ($filename_list as $i => $val) {
637 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
638 if (!empty($mimefilename_list[$i])) {
639 $attachment->setFilename($mimefilename_list[$i]);
641 $this->message->attach($attachment);
645 if (!empty($this->addr_cc)) {
649 $this->errors[] = $e->getMessage();
652 if (!empty($this->addr_bcc)) {
656 $this->errors[] = $e->getMessage();
659 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
661 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
663 $this->errors[] = $e->getMessage();
669 $this->error =
'Bad value for sendmode';
680 global $conf, $db, $langs, $hookmanager;
682 $errorlevel = error_reporting();
688 if (!is_object($hookmanager)) {
689 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
692 $hookmanager->initHooks(array(
'mail'));
694 $parameters = array();
696 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
698 $this->error =
"Error in hook maildao sendMail ".$reshook;
699 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
707 $sendingmode = $this->sendmode;
708 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
710 $listofmethods = array();
711 $listofmethods[
'mail'] =
'PHP mail function';
713 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
717 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
718 $linktoadminemailend =
'</a>';
719 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
720 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
721 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
722 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
724 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
725 $this->errors[] = $langs->trans(
"MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
728 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
734 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
736 $tmparray1 = explode(
',', $this->addr_to);
737 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
738 $this->error =
'Too much recipients in to:';
739 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
743 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
745 $tmparray2 = explode(
',', $this->addr_cc);
746 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
747 $this->error =
'Too much recipients in cc:';
748 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
752 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
754 $tmparray3 = explode(
',', $this->addr_bcc);
755 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
756 $this->error =
'Too much recipients in bcc:';
757 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
761 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
763 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
764 $this->error =
'Too much recipients in to:, cc:, bcc:';
765 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
769 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
770 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
771 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
772 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
773 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
774 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
775 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
776 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
777 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
778 if (!empty($this->sendcontext)) {
779 $smtpContextKey = strtoupper($this->sendcontext);
781 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
782 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
783 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
784 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
785 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
786 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
787 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
788 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
789 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
790 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
795 if ($this->sendmode ==
'mail') {
798 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
803 if (isset($_SERVER[
"WINDIR"])) {
804 if (empty($this->addr_from)) {
805 $this->addr_from =
'robot@example.com';
807 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
820 if ($res && !$this->subject) {
821 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
822 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
826 if ($res && !$dest) {
827 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
828 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
833 $additionnalparam =
'';
840 $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) :
''));
843 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
847 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
851 if (preg_match(
'/^win/i', PHP_OS)) {
854 if (preg_match(
'/^mac/i', PHP_OS)) {
858 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
860 $this->message = stripslashes($this->message);
867 $subjecttouse = $this->subject;
872 if (!empty($additionnalparam)) {
873 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
875 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
879 $langs->load(
"errors");
880 $this->error =
"Failed to send mail with php mail";
882 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
884 $this->error .=
".<br>";
885 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
886 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
892 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
896 if (isset($_SERVER[
"WINDIR"])) {
897 @ini_restore(
'sendmail_from');
905 ini_restore(
'smtp_port');
907 } elseif ($this->sendmode ==
'smtps') {
908 if (!is_object($this->smtps)) {
909 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
910 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
916 $this->smtps->setTransportType(0);
919 if (empty($conf->global->$keyforsmtpserver)) {
920 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
922 if (empty($conf->global->$keyforsmtpport)) {
923 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
929 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
932 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
935 $server = ($secure ? $secure.
'://' :
'').$server;
939 $this->smtps->setHost($server);
940 $this->smtps->setPort($port);
944 if (!empty($conf->global->$keyforsmtpid)) {
945 $loginid = $conf->global->$keyforsmtpid;
946 $this->smtps->setID($loginid);
948 if (!empty($conf->global->$keyforsmtppw)) {
949 $loginpass = $conf->global->$keyforsmtppw;
950 $this->smtps->setPW($loginpass);
954 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
959 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
960 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
962 $keyforprovider =
'';
964 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
965 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
967 if (!empty($supportedoauth2array)) {
968 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
970 $OAUTH_SERVICENAME =
'Unknown';
973 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
975 $storage =
new DoliStorage($db, $conf, $keyforprovider);
977 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
980 if (is_object($tokenobj)) {
981 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
984 if (is_object($tokenobj) && $expire) {
985 $credentials =
new Credentials(
990 $serviceFactory = new \OAuth\ServiceFactory();
991 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
993 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
995 $refreshtoken = $tokenobj->getRefreshToken();
996 $tokenobj = $apiService->refreshAccessToken($tokenobj);
997 $tokenobj->setRefreshToken($refreshtoken);
998 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1001 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1002 if (is_object($tokenobj)) {
1003 $this->smtps->setToken($tokenobj->getAccessToken());
1005 $this->error =
"Token not found";
1009 $this->error = $e->getMessage();
1010 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1015 $from = $this->smtps->getFrom(
'org');
1016 if ($res && !$from) {
1017 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1018 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1021 $dest = $this->smtps->getTo();
1022 if ($res && !$dest) {
1023 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1024 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1032 $this->smtps->setDebug(
true);
1035 $result = $this->smtps->sendMsg();
1043 $smtperrorcode = $this->smtps->lastretval;
1044 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1046 if ($smtperrorcode ==
'421') {
1061 $result = $this->smtps->getErrors();
1062 if (empty($this->error) && empty($result)) {
1063 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1066 if (empty($this->error)) {
1067 $this->error = $result;
1069 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1077 } elseif ($this->sendmode ==
'swiftmailer') {
1080 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1083 if (empty($conf->global->$keyforsmtpserver)) {
1084 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1086 if (empty($conf->global->$keyforsmtpport)) {
1087 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1093 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1096 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1100 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalString($keyforsmtpport), $secure);
1102 if (!empty($conf->global->$keyforsmtpid)) {
1103 $this->transport->setUsername($conf->global->$keyforsmtpid);
1105 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1106 $this->transport->setPassword($conf->global->$keyforsmtppw);
1109 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1114 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1115 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1117 $keyforprovider =
'';
1119 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1120 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1122 $OAUTH_SERVICENAME =
'Unknown';
1123 if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array)
1124 && array_key_exists(
'name', $supportedoauth2array[$keyforsupportedoauth2array])
1125 && !empty($supportedoauth2array[$keyforsupportedoauth2array][
'name'])) {
1126 $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array][
'name'].(!empty($keyforprovider) ?
'-'.$keyforprovider :
'');
1129 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1131 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1134 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1137 if (is_object($tokenobj)) {
1138 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1141 if (is_object($tokenobj) && $expire) {
1142 $credentials =
new Credentials(
1147 $serviceFactory = new \OAuth\ServiceFactory();
1148 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1150 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1152 $refreshtoken = $tokenobj->getRefreshToken();
1153 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1154 $tokenobj->setRefreshToken($refreshtoken);
1155 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1157 if (is_object($tokenobj)) {
1158 $this->transport->setAuthMode(
'XOAUTH2');
1159 $this->transport->setPassword($tokenobj->getAccessToken());
1161 $this->errors[] =
"Token not found";
1165 $this->errors[] = $e->getMessage();
1166 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1170 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1175 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1176 $this->message->setEncoder($contentEncoderBase64);
1179 $this->mailer =
new Swift_Mailer($this->transport);
1183 $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
1184 $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
1185 $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
1186 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1187 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1192 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1195 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1201 $failedRecipients = array();
1203 $result = $this->mailer->send($this->message, $failedRecipients);
1205 $this->errors[] = $e->getMessage();
1212 if (!empty($this->error) || !empty($this->errors) || !$result) {
1213 if (!empty($failedRecipients)) {
1214 $this->error =
'Transport failed for the following addresses: "' . join(
'", "', $failedRecipients) .
'".';
1215 $this->errors[] = $this->error;
1217 dol_syslog(
"CMailFile::sendfile: mail end error=". join(
' ', $this->errors), LOG_ERR);
1224 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1230 return 'Bad value for sendmode';
1234 foreach ($this->html_images as $val) {
1235 if (!empty($val[
'type']) && $val[
'type'] ==
'cidfromdata') {
1240 $parameters = array(
'sent' => $res);
1242 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1244 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1245 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1250 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1251 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1254 error_reporting($errorlevel);