192 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 =
'')
194 global $conf, $dolibarr_main_data_root, $user;
196 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);
197 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
201 if (is_array($mimefilename_list)) {
202 foreach ($mimefilename_list as $key => $val) {
209 $this->sendcontext = $sendcontext;
212 $this->sendmode =
'';
213 if (!empty($this->sendcontext)) {
214 $smtpContextKey = strtoupper($this->sendcontext);
216 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
217 $this->sendmode = $smtpContextSendMode;
220 if (empty($this->sendmode)) {
230 $moreinheader .=
"Feedback-ID: ".$trackid.
':'.dol_getprefix(
'email').
":dolib\r\n";
236 $this->eol2 =
"\r\n";
240 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
244 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
247 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"), 3);
250 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"), 3);
252 if (empty($subject)) {
253 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
254 $this->error =
'ErrorSubjectIsRequired';
258 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
263 if ($msgishtml == -1) {
264 $this->msgishtml = 0;
266 $this->msgishtml = 1;
269 $this->msgishtml = $msgishtml;
272 global $dolibarr_main_url_root;
275 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
276 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
280 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
283 $this->msgishtml = 1;
285 dol_syslog(
"CMailFile::CMailfile: msgishtml=".$this->msgishtml);
288 if ($this->msgishtml) {
297 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
299 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
300 $this->error =
'ErrorInAddAttachmentsImageBaseOnMedia';
309 if ($resultImageData < 0) {
310 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
311 $this->error =
'ErrorInAddAttachmentsImageBaseIsSrcData';
314 $findimg += $resultImageData;
319 foreach ($this->html_images as $i => $val) {
320 if ($this->html_images[$i]) {
321 $this->atleastoneimage = 1;
322 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
323 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
325 $posindice = count($filename_list);
326 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
327 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
328 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
330 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
333 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
335 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
344 if (is_array($filename_list)) {
345 foreach ($filename_list as $i => $val) {
346 if ($filename_list[$i]) {
347 $this->atleastonefile = 1;
348 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);
357 foreach ($listofemailstoadd as $key => $val) {
358 $emailtoadd = $listofemailstoadd[$key];
359 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
360 if (!empty($user) && !empty($user->email)) {
361 $emailtoadd = $user->email;
366 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
370 $listofemailstoadd[$key] = $emailtoadd;
372 unset($listofemailstoadd[$key]);
375 if (!empty($listofemailstoadd)) {
376 $addr_bcc .= ($addr_bcc ?
', ' :
'').implode(
', ', $listofemailstoadd);
384 $tabto = explode(
",", $to);
385 $listofemailstonotsendto = explode(
',',
getDolGlobalString(
'MAIN_MAIL_FORCE_NOT_SENDING_TO'));
386 foreach ($tabto as $key => $addrto) {
388 if (in_array($addrto[0], $listofemailstonotsendto)) {
396 $to = implode(
',', $tabto);
400 $tabcc = explode(
',', $addr_cc);
401 foreach ($tabcc as $key => $cc) {
403 if (in_array($cc[0], $listofemailstonotsendto)) {
411 $addr_cc = implode(
',', $tabcc);
415 $tabbcc = explode(
',', $addr_bcc);
416 foreach ($tabbcc as $key => $bcc) {
418 if (in_array($bcc[0], $listofemailstonotsendto)) {
419 unset($tabbcc[$key]);
426 $addr_bcc = implode(
',', $tabbcc);
430 if (empty($replyto)) {
438 $this->subject = $subject;
444 $this->deliveryreceipt = $deliveryreceipt;
447 $this->trackid = $trackid;
448 $this->in_reply_to = $in_reply_to;
449 $this->references = $references;
451 $this->filename_list = $filename_list;
452 $this->mimetype_list = $mimetype_list;
453 $this->mimefilename_list = $mimefilename_list;
454 $this->cid_list = $cid_list;
459 $this->addr_bcc =
'';
462 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
463 if (!empty($this->sendcontext)) {
464 $smtpContextKey = strtoupper($this->sendcontext);
466 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
467 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
471 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
475 if ($this->sendmode ==
'mail') {
486 if (!empty($moreinheader)) {
487 $smtp_headers .= $moreinheader;
493 if (!empty($this->html)) {
506 if (!empty($this->atleastonefile)) {
507 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
511 $this->headers = $smtp_headers.$mime_headers;
514 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
517 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
518 $this->message .= $text_body.$files_encoded;
519 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
520 } elseif ($this->sendmode ==
'smtps') {
523 $host = dol_getprefix(
'email');
525 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
526 $smtps =
new SMTPs();
527 $smtps->setCharSet($conf->file->character_set_client);
530 $subjecttouse = $this->subject;
535 $smtps->setSubject($subjecttouse);
540 $smtps->setTrackId($this->trackid);
542 if (!empty($this->in_reply_to)) {
543 $smtps->setInReplyTo($this->in_reply_to);
545 if (!empty($this->references)) {
546 $smtps->setReferences($this->references);
549 if (!empty($moreinheader)) {
550 $smtps->setMoreInHeader($moreinheader);
555 if (!empty($this->html)) {
565 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
567 if ($this->msgishtml) {
568 $smtps->setBodyContent($msg,
'html');
570 $smtps->setBodyContent($msg,
'plain');
573 if ($this->atleastoneimage) {
574 foreach ($this->images_encoded as $img) {
575 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
579 if (!empty($this->atleastonefile)) {
580 foreach ($filename_list as $i => $val) {
581 $content = file_get_contents($filename_list[$i]);
582 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], (empty($cid_list[$i]) ?
'' : $cid_list[$i]));
586 $smtps->setCC($this->addr_cc);
587 $smtps->setBCC($this->addr_bcc);
588 $smtps->setErrorsTo($this->errors_to);
589 $smtps->setDeliveryReceipt($this->deliveryreceipt);
591 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
594 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
596 $this->smtps = $smtps;
597 } elseif ($this->sendmode ==
'swiftmailer') {
600 $host = dol_getprefix(
'email');
602 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
605 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
607 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
611 $this->message =
new Swift_Message();
614 $headers = $this->message->getHeaders();
616 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
617 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
618 $headerID = $this->msgid;
619 $msgid = $headers->get(
'Message-ID');
620 $msgid->setId($headerID);
623 if (!empty($this->in_reply_to)) {
624 $headers->addIdHeader(
'In-Reply-To', $this->in_reply_to);
627 if (!empty($this->references)) {
628 $headers->addIdHeader(
'References', $this->references);
631 if (!empty($moreinheader)) {
632 $moreinheaderarray = preg_split(
'/[\r\n]+/', $moreinheader);
633 foreach ($moreinheaderarray as $moreinheaderval) {
634 $moreinheadervaltmp = explode(
':', $moreinheaderval, 2);
635 if (!empty($moreinheadervaltmp[0]) && !empty($moreinheadervaltmp[1])) {
636 $headers->addTextHeader($moreinheadervaltmp[0], $moreinheadervaltmp[1]);
643 $this->message->setSubject($this->subject);
645 $this->errors[] = $e->getMessage();
650 if (!empty($this->addr_from)) {
654 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
655 $adressEmailFrom = array();
656 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
657 $adressEmailFrom = reset($adressEmailFrom);
658 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
659 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
667 $this->errors[] = $e->getMessage();
672 if (!empty($this->addr_to)) {
676 $this->errors[] = $e->getMessage();
680 if (!empty($this->reply_to)) {
684 $this->errors[] = $e->getMessage();
688 if (!empty($this->errors_to)) {
690 $headers->addTextHeader(
'Errors-To', $this->
getArrayAddress($this->errors_to));
692 $this->errors[] = $e->getMessage();
697 $this->message->setCharSet($conf->file->character_set_client);
699 $this->errors[] = $e->getMessage();
702 if (!empty($this->html)) {
711 if ($this->atleastoneimage) {
712 foreach ($this->html_images as $img) {
714 $attachment = Swift_Image::fromPath($img[
'fullpath']);
716 $imgcid = $this->message->embed($attachment);
718 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
720 foreach ($this->images_encoded as $img) {
722 $attachment = Swift_Image::fromPath($img[
'fullpath']);
724 $imgcid = $this->message->embed($attachment);
726 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
730 if ($this->msgishtml) {
731 $this->message->setBody($msg,
'text/html');
733 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
735 $this->message->setBody($msg,
'text/plain');
737 $this->message->addPart(
dol_nl2br($msg),
'text/html');
740 if (!empty($this->atleastonefile)) {
741 foreach ($filename_list as $i => $val) {
743 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
744 if (!empty($mimefilename_list[$i])) {
745 $attachment->setFilename($mimefilename_list[$i]);
747 $this->message->attach($attachment);
751 if (!empty($this->addr_cc)) {
755 $this->errors[] = $e->getMessage();
758 if (!empty($this->addr_bcc)) {
762 $this->errors[] = $e->getMessage();
766 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
768 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
770 $this->errors[] = $e->getMessage();
776 $this->error =
'Bad value for sendmode';
789 global $conf, $db, $langs, $hookmanager;
791 $errorlevel = error_reporting();
797 if (!is_object($hookmanager)) {
798 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
801 $hookmanager->initHooks(array(
'mail'));
803 $parameters = array();
805 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
807 $this->error =
"Error in hook maildao sendMail ".$reshook;
808 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
816 $sendingmode = $this->sendmode;
817 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
819 $listofmethods = array();
820 $listofmethods[
'mail'] =
'PHP mail function';
822 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
826 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
827 $linktoadminemailend =
'</a>';
828 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
829 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
830 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
831 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
833 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
834 $this->errors[] = $langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
837 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
843 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
845 $tmparray1 = explode(
',', $this->addr_to);
846 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
847 $this->error =
'Too much recipients in to:';
848 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
852 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
854 $tmparray2 = explode(
',', $this->addr_cc);
855 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
856 $this->error =
'Too much recipients in cc:';
857 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
861 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
863 $tmparray3 = explode(
',', $this->addr_bcc);
864 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
865 $this->error =
'Too much recipients in bcc:';
866 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
870 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
872 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
873 $this->error =
'Too much recipients in to:, cc:, bcc:';
874 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
878 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
879 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
880 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
881 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
882 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
883 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
884 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
885 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
886 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
887 if (!empty($this->sendcontext)) {
888 $smtpContextKey = strtoupper($this->sendcontext);
890 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
891 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
892 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
893 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
894 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
895 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
896 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
897 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
898 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
899 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
904 if ($this->sendmode ==
'mail') {
907 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
912 if (isset($_SERVER[
"WINDIR"])) {
913 if (empty($this->addr_from)) {
914 $this->addr_from =
'robot@example.com';
916 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
929 if ($res && !$this->subject) {
930 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
931 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
935 if ($res && !$dest) {
936 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
937 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
942 $additionnalparam =
'';
949 $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) :
''));
952 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
956 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
960 if (preg_match(
'/^win/i', PHP_OS)) {
963 if (preg_match(
'/^mac/i', PHP_OS)) {
967 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
969 $this->message = stripslashes($this->message);
976 $subjecttouse = $this->subject;
981 if (!empty($additionnalparam)) {
982 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
984 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
988 $langs->load(
"errors");
989 $this->error =
"Failed to send mail with php mail";
991 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
993 $this->error .=
".<br>";
994 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
995 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1001 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1005 if (isset($_SERVER[
"WINDIR"])) {
1006 @ini_restore(
'sendmail_from');
1011 ini_restore(
'SMTP');
1014 ini_restore(
'smtp_port');
1016 } elseif ($this->sendmode ==
'smtps') {
1017 if (!is_object($this->smtps)) {
1018 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1019 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1025 $this->smtps->setTransportType(0);
1028 if (empty($conf->global->$keyforsmtpserver)) {
1029 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1031 if (empty($conf->global->$keyforsmtpport)) {
1032 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1038 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1041 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1044 $server = ($secure ? $secure.
'://' :
'').$server;
1048 $this->smtps->setHost($server);
1049 $this->smtps->setPort($port);
1053 if (!empty($conf->global->$keyforsmtpid)) {
1055 $this->smtps->setID($loginid);
1057 if (!empty($conf->global->$keyforsmtppw)) {
1059 $this->smtps->setPW($loginpass);
1063 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1068 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1069 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1071 $keyforprovider =
'';
1073 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1074 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1076 if (!empty($supportedoauth2array)) {
1077 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1079 $OAUTH_SERVICENAME =
'Unknown';
1082 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1084 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1086 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1090 if (is_object($tokenobj)) {
1091 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1094 if (is_object($tokenobj) && $expire) {
1095 $credentials =
new Credentials(
1100 $serviceFactory = new \OAuth\ServiceFactory();
1101 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1103 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1105 $refreshtoken = $tokenobj->getRefreshToken();
1106 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1107 $tokenobj->setRefreshToken($refreshtoken);
1108 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1110 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1113 if (is_object($tokenobj)) {
1114 $this->smtps->setToken($tokenobj->getAccessToken());
1116 $this->error =
"Token not found";
1120 $this->error = $e->getMessage();
1121 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1126 $from = $this->smtps->getFrom(
'org');
1127 if ($res && !$from) {
1128 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1129 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1132 $dest = $this->smtps->getTo();
1133 if ($res && !$dest) {
1134 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1135 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1143 $this->smtps->setDebug(
true);
1146 $result = $this->smtps->sendMsg();
1154 $smtperrorcode = $this->smtps->lastretval;
1155 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1157 if ($smtperrorcode ==
'421') {
1172 $result = $this->smtps->getErrors();
1173 if (empty($this->error) && empty($result)) {
1174 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1177 if (empty($this->error)) {
1178 $this->error = $result;
1180 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1188 } elseif ($this->sendmode ==
'swiftmailer') {
1191 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1194 if (empty($conf->global->$keyforsmtpserver)) {
1195 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1197 if (empty($conf->global->$keyforsmtpport)) {
1198 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1204 if (!empty($conf->global->$keyfortls) && function_exists(
'openssl_open')) {
1207 if (!empty($conf->global->$keyforstarttls) && function_exists(
'openssl_open')) {
1211 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalString($keyforsmtpport), $secure);
1213 if (!empty($conf->global->$keyforsmtpid)) {
1214 $this->transport->setUsername($conf->global->$keyforsmtpid);
1216 if (!empty($conf->global->$keyforsmtppw) &&
getDolGlobalString($keyforsmtpauthtype) !=
"XOAUTH2") {
1217 $this->transport->setPassword($conf->global->$keyforsmtppw);
1220 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1225 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1226 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1228 $keyforprovider =
'';
1230 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1231 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1233 $OAUTH_SERVICENAME =
'Unknown';
1234 if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array)
1235 && array_key_exists(
'name', $supportedoauth2array[$keyforsupportedoauth2array])
1236 && !empty($supportedoauth2array[$keyforsupportedoauth2array][
'name'])) {
1237 $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array][
'name'].(!empty($keyforprovider) ?
'-'.$keyforprovider :
'');
1240 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1242 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1245 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1249 if (is_object($tokenobj)) {
1250 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1253 if (is_object($tokenobj) && $expire) {
1254 $credentials =
new Credentials(
1259 $serviceFactory = new \OAuth\ServiceFactory();
1260 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1262 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1264 $refreshtoken = $tokenobj->getRefreshToken();
1265 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1266 $tokenobj->setRefreshToken($refreshtoken);
1267 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1269 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1272 if (is_object($tokenobj)) {
1273 $this->transport->setAuthMode(
'XOAUTH2');
1274 $this->transport->setPassword($tokenobj->getAccessToken());
1276 $this->errors[] =
"Token not found";
1280 $this->errors[] = $e->getMessage();
1281 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1285 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1290 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1291 $this->message->setEncoder($contentEncoderBase64);
1294 $this->mailer =
new Swift_Mailer($this->transport);
1301 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1302 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1307 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1310 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1316 $failedRecipients = array();
1318 $result = $this->mailer->send($this->message, $failedRecipients);
1320 $this->errors[] = $e->getMessage();
1327 if (!empty($this->error) || !empty($this->errors) || !$result) {
1328 if (!empty($failedRecipients)) {
1329 $this->errors[] =
'Transport failed for the following addresses: "' . implode(
'", "', $failedRecipients) .
'".';
1331 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1338 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1344 $this->error =
'Bad value for sendmode';
1349 foreach ($this->html_images as $val) {
1350 if (!empty($val[
'type']) && $val[
'type'] ==
'cidfromdata') {
1355 $parameters = array(
'sent' => $res);
1357 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1359 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1360 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1365 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1366 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1369 error_reporting($errorlevel);