228 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 =
'')
230 global $conf, $dolibarr_main_data_root, $user;
232 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);
233 dol_syslog(
"CMailFile::CMailfile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
237 if (is_array($mimefilename_list)) {
238 foreach ($mimefilename_list as $key => $val) {
245 $this->sendcontext = $sendcontext;
248 $this->sendmode =
'';
249 if (!empty($this->sendcontext)) {
250 $smtpContextKey = strtoupper($this->sendcontext);
252 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
253 $this->sendmode = $smtpContextSendMode;
256 if (empty($this->sendmode)) {
266 $moreinheader .=
"Feedback-ID: ".$trackid.
':'.dol_getprefix(
'email').
":dolib\r\n";
272 $this->eol2 =
"\r\n";
276 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
280 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
283 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"), 3);
286 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"), 3);
288 if (empty($subject)) {
289 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty subject");
290 $this->error =
'ErrorSubjectIsRequired';
294 dol_syslog(
"CMailFile::CMailfile: Try to send an email with empty body");
299 if ($msgishtml == -1) {
300 $this->msgishtml = 0;
302 $this->msgishtml = 1;
305 $this->msgishtml = $msgishtml;
308 global $dolibarr_main_url_root;
311 $urlwithouturlroot = preg_replace(
'/'.preg_quote(DOL_URL_ROOT,
'/').
'$/i',
'', trim($dolibarr_main_url_root));
312 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
316 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
319 $this->msgishtml = 1;
321 dol_syslog(
"CMailFile::CMailfile: msgishtml=".$this->msgishtml);
324 if ($this->msgishtml) {
333 $findimg = $this->
findHtmlImages($dolibarr_main_data_root.
'/medias');
335 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImages");
336 $this->error =
'ErrorInAddAttachmentsImageBaseOnMedia';
345 if ($resultImageData < 0) {
346 dol_syslog(
"CMailFile::CMailfile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
347 $this->error =
'ErrorInAddAttachmentsImageBaseIsSrcData';
350 $findimg += $resultImageData;
355 foreach ($this->html_images as $i => $val) {
356 if ($this->html_images[$i]) {
357 $this->atleastoneimage = 1;
358 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
359 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
361 $posindice = count($filename_list);
362 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
363 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
364 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
366 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
369 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
371 dol_syslog(
"CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
380 if (is_array($filename_list)) {
381 foreach ($filename_list as $i => $val) {
382 if ($filename_list[$i]) {
383 $this->atleastonefile = 1;
384 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);
393 foreach ($listofemailstoadd as $key => $val) {
394 $emailtoadd = $listofemailstoadd[$key];
395 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
396 if (!empty($user) && !empty($user->email)) {
397 $emailtoadd = $user->email;
402 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
406 $listofemailstoadd[$key] = $emailtoadd;
408 unset($listofemailstoadd[$key]);
411 if (!empty($listofemailstoadd)) {
412 $addr_bcc .= ($addr_bcc ?
', ' :
'').implode(
', ', $listofemailstoadd);
420 $tabto = explode(
",", $to);
421 $listofemailstonotsendto = explode(
',',
getDolGlobalString(
'MAIN_MAIL_FORCE_NOT_SENDING_TO'));
422 foreach ($tabto as $key => $addrto) {
424 if (in_array($addrto[0], $listofemailstonotsendto)) {
432 $to = implode(
',', $tabto);
436 $tabcc = explode(
',', $addr_cc);
437 foreach ($tabcc as $key => $cc) {
439 if (in_array($cc[0], $listofemailstonotsendto)) {
447 $addr_cc = implode(
',', $tabcc);
451 $tabbcc = explode(
',', $addr_bcc);
452 foreach ($tabbcc as $key => $bcc) {
454 if (in_array($bcc[0], $listofemailstonotsendto)) {
455 unset($tabbcc[$key]);
462 $addr_bcc = implode(
',', $tabbcc);
466 if (empty($replyto)) {
474 $this->subject = $subject;
480 $this->deliveryreceipt = $deliveryreceipt;
483 $this->trackid = $trackid;
484 $this->in_reply_to = $in_reply_to;
485 $this->references = $references;
487 $this->filename_list = $filename_list;
488 $this->mimetype_list = $mimetype_list;
489 $this->mimefilename_list = $mimefilename_list;
490 $this->cid_list = $cid_list;
495 $this->addr_bcc =
'';
498 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
499 if (!empty($this->sendcontext)) {
500 $smtpContextKey = strtoupper($this->sendcontext);
502 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
503 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
507 dol_syslog(
"CMailFile::CMailfile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
511 if ($this->sendmode ==
'mail') {
522 if (!empty($moreinheader)) {
523 $smtp_headers .= $moreinheader;
529 if (!empty($this->html)) {
542 if (!empty($this->atleastonefile)) {
543 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
547 $this->headers = $smtp_headers.$mime_headers;
550 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
553 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
554 $this->message .= $text_body.$files_encoded;
555 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
556 } elseif ($this->sendmode ==
'smtps') {
559 $host = dol_getprefix(
'email');
561 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
562 $smtps =
new SMTPs();
563 $smtps->setCharSet($conf->file->character_set_client);
566 $subjecttouse = $this->subject;
571 $smtps->setSubject($subjecttouse);
576 $smtps->setTrackId($this->trackid);
578 if (!empty($this->in_reply_to)) {
579 $smtps->setInReplyTo($this->in_reply_to);
581 if (!empty($this->references)) {
582 $smtps->setReferences($this->references);
585 if (!empty($moreinheader)) {
586 $smtps->setMoreInHeader($moreinheader);
591 if (!empty($this->html)) {
601 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
603 if ($this->msgishtml) {
604 $smtps->setBodyContent($msg,
'html');
606 $smtps->setBodyContent($msg,
'plain');
609 if ($this->atleastoneimage) {
610 foreach ($this->images_encoded as $img) {
611 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
615 if (!empty($this->atleastonefile)) {
616 foreach ($filename_list as $i => $val) {
617 $content = file_get_contents($filename_list[$i]);
618 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], (empty($cid_list[$i]) ?
'' : $cid_list[$i]));
622 $smtps->setCC($this->addr_cc);
623 $smtps->setBCC($this->addr_bcc);
624 $smtps->setErrorsTo($this->errors_to);
625 $smtps->setDeliveryReceipt($this->deliveryreceipt);
627 $smtps->setOptions(array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true)));
630 $this->msgid = time().
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
632 $this->smtps = $smtps;
633 } elseif ($this->sendmode ==
'swiftmailer') {
636 $host = dol_getprefix(
'email');
638 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
641 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
643 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
647 $this->message =
new Swift_Message();
650 $headers = $this->message->getHeaders();
652 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
653 $this->msgid = time().
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
654 $headerID = $this->msgid;
655 $msgid = $headers->get(
'Message-ID');
656 if ($msgid instanceof Swift_Mime_Headers_IdentificationHeader) {
657 $msgid->setId($headerID);
661 if (!empty($this->in_reply_to)) {
662 $headers->addIdHeader(
'In-Reply-To', $this->in_reply_to);
665 if (!empty($this->references)) {
666 $headers->addIdHeader(
'References', $this->references);
669 if (!empty($moreinheader)) {
670 $moreinheaderarray = preg_split(
'/[\r\n]+/', $moreinheader);
671 foreach ($moreinheaderarray as $moreinheaderval) {
672 $moreinheadervaltmp = explode(
':', $moreinheaderval, 2);
673 if (!empty($moreinheadervaltmp[0]) && !empty($moreinheadervaltmp[1])) {
674 $headers->addTextHeader($moreinheadervaltmp[0], $moreinheadervaltmp[1]);
681 $this->message->setSubject($this->subject);
683 $this->errors[] = $e->getMessage();
688 if (!empty($this->addr_from)) {
692 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
693 $adressEmailFrom = array();
694 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
695 $adressEmailFrom = reset($adressEmailFrom);
696 if ($emailMatchs !==
false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
697 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
705 $this->errors[] = $e->getMessage();
710 if (!empty($this->addr_to)) {
714 $this->errors[] = $e->getMessage();
718 if (!empty($this->reply_to)) {
722 $this->errors[] = $e->getMessage();
726 if (!empty($this->errors_to)) {
728 $headers->addMailboxHeader(
'Errors-To', $this->
getArrayAddress($this->errors_to));
730 $this->errors[] = $e->getMessage();
735 $this->message->setCharSet($conf->file->character_set_client);
737 $this->errors[] = $e->getMessage();
740 if (!empty($this->html)) {
749 if ($this->atleastoneimage) {
750 foreach ($this->html_images as $img) {
752 $attachment = Swift_Image::fromPath($img[
'fullpath']);
754 $imgcid = $this->message->embed($attachment);
756 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
758 foreach ($this->images_encoded as $img) {
760 $attachment = Swift_Image::fromPath($img[
'fullpath']);
762 $imgcid = $this->message->embed($attachment);
764 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
768 if ($this->msgishtml) {
769 $this->message->setBody($msg,
'text/html');
771 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
773 $this->message->setBody($msg,
'text/plain');
775 $this->message->addPart(
dol_nl2br($msg),
'text/html');
778 if (!empty($this->atleastonefile)) {
779 foreach ($filename_list as $i => $val) {
781 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
782 if (!empty($mimefilename_list[$i])) {
783 $attachment->setFilename($mimefilename_list[$i]);
785 $this->message->attach($attachment);
789 if (!empty($this->addr_cc)) {
793 $this->errors[] = $e->getMessage();
796 if (!empty($this->addr_bcc)) {
800 $this->errors[] = $e->getMessage();
804 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
806 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
808 $this->errors[] = $e->getMessage();
814 $this->error =
'Bad value for sendmode';
827 global $conf, $db, $langs, $hookmanager;
829 $errorlevel = error_reporting();
835 if (!is_object($hookmanager)) {
836 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
839 $hookmanager->initHooks(array(
'mail'));
841 $parameters = array();
843 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
845 $this->error =
"Error in hook maildao sendMail ".$reshook;
846 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
851 dol_syslog(
"A hook has replaced code to send email", LOG_DEBUG);
855 $sendingmode = $this->sendmode;
856 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
858 $listofmethods = array();
859 $listofmethods[
'mail'] =
'PHP mail function';
861 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
865 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
866 $linktoadminemailend =
'</a>';
867 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
868 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
869 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
870 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
872 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
873 $this->errors[] = $langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
876 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
882 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
884 $tmparray1 = explode(
',', $this->addr_to);
885 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
886 $this->error =
'Too much recipients in to:';
887 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
891 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
893 $tmparray2 = explode(
',', $this->addr_cc);
894 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
895 $this->error =
'Too much recipients in cc:';
896 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
900 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
902 $tmparray3 = explode(
',', $this->addr_bcc);
903 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
904 $this->error =
'Too much recipients in bcc:';
905 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
909 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
911 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
912 $this->error =
'Too much recipients in to:, cc:, bcc:';
913 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
917 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
918 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
919 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
920 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
921 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
922 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
923 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
924 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
925 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
926 if (!empty($this->sendcontext)) {
927 $smtpContextKey = strtoupper($this->sendcontext);
929 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
930 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
931 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
932 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
933 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
934 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
935 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
936 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
937 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
938 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
943 if ($this->sendmode ==
'mail') {
946 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_DEBUG);
951 if (isset($_SERVER[
"WINDIR"])) {
952 if (empty($this->addr_from)) {
953 $this->addr_from =
'robot@example.com';
955 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
968 if ($res && !$this->subject) {
969 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
970 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
974 if ($res && !$dest) {
975 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
976 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
981 $additionnalparam =
'';
988 $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) :
''));
991 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
995 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
999 if (preg_match(
'/^win/i', PHP_OS)) {
1002 if (preg_match(
'/^mac/i', PHP_OS)) {
1006 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
1008 $this->message = stripslashes($this->message);
1015 $subjecttouse = $this->subject;
1020 if (!empty($additionnalparam)) {
1021 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
1023 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
1027 $langs->load(
"errors");
1028 $this->error =
"Failed to send mail with php mail";
1030 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
1032 $this->error .=
".<br>";
1033 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
1034 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1040 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1044 if (isset($_SERVER[
"WINDIR"])) {
1045 @ini_restore(
'sendmail_from');
1050 ini_restore(
'SMTP');
1053 ini_restore(
'smtp_port');
1055 } elseif ($this->sendmode ==
'smtps') {
1056 if (!is_object($this->smtps)) {
1057 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1058 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1064 $this->smtps->setTransportType(0);
1067 if (empty($conf->global->$keyforsmtpserver)) {
1068 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1070 if (empty($conf->global->$keyforsmtpport)) {
1071 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1083 $server = ($secure ? $secure.
'://' :
'').$server;
1087 $this->smtps->setHost($server);
1088 $this->smtps->setPort($port);
1094 $this->smtps->setID($loginid);
1098 $this->smtps->setPW($loginpass);
1102 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1107 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1108 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1110 $keyforprovider =
'';
1112 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1113 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1115 if (!empty($supportedoauth2array)) {
1116 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1118 $OAUTH_SERVICENAME =
'Unknown';
1121 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1123 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1125 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1129 if (is_object($tokenobj)) {
1130 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1133 if (is_object($tokenobj) && $expire) {
1134 $credentials =
new Credentials(
1139 $serviceFactory = new \OAuth\ServiceFactory();
1140 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1142 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1145 $refreshtoken = $tokenobj->getRefreshToken();
1147 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1149 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1150 $tokenobj->setRefreshToken($refreshtoken);
1151 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1154 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1157 if (is_object($tokenobj)) {
1158 $this->smtps->setToken($tokenobj->getAccessToken());
1160 $this->error =
"Token not found";
1164 $this->error = $e->getMessage();
1165 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1170 $from = $this->smtps->getFrom(
'org');
1171 if ($res && !$from) {
1172 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1173 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1176 $dest = $this->smtps->getTo();
1177 if ($res && !$dest) {
1178 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1179 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1187 $this->smtps->setDebug(
true);
1190 $result = $this->smtps->sendMsg();
1198 $smtperrorcode = $this->smtps->lastretval;
1199 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1201 if ($smtperrorcode ==
'421') {
1216 $result = $this->smtps->getErrors();
1217 if (empty($this->error) && empty($result)) {
1218 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1221 if (empty($this->error)) {
1222 $this->error = $result;
1224 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1232 } elseif ($this->sendmode ==
'swiftmailer') {
1235 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1238 if (empty($conf->global->$keyforsmtpserver)) {
1239 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1241 if (empty($conf->global->$keyforsmtpport)) {
1242 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1255 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalInt($keyforsmtpport), $secure);
1258 $this->transport->setUsername($conf->global->$keyforsmtpid);
1261 $this->transport->setPassword($conf->global->$keyforsmtppw);
1264 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1269 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1270 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1272 $keyforprovider =
'';
1274 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1275 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1277 $OAUTH_SERVICENAME =
'Unknown';
1278 if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array)
1279 && array_key_exists(
'name', $supportedoauth2array[$keyforsupportedoauth2array])
1280 && !empty($supportedoauth2array[$keyforsupportedoauth2array][
'name'])) {
1281 $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array][
'name'].(!empty($keyforprovider) ?
'-'.$keyforprovider :
'');
1284 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1286 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1289 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1293 if (is_object($tokenobj)) {
1294 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1297 if (is_object($tokenobj) && $expire) {
1298 $credentials =
new Credentials(
1303 $serviceFactory = new \OAuth\ServiceFactory();
1304 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1306 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1307 $refreshtoken = $tokenobj->getRefreshToken();
1309 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1312 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1313 $tokenobj->setRefreshToken($refreshtoken);
1314 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1316 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1320 if (is_object($tokenobj)) {
1321 $this->transport->setAuthMode(
'XOAUTH2');
1322 $this->transport->setPassword($tokenobj->getAccessToken());
1324 $this->errors[] =
"Token not found";
1328 $this->errors[] = $e->getMessage();
1329 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1333 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1338 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1339 $this->message->setEncoder($contentEncoderBase64);
1342 $this->mailer =
new Swift_Mailer($this->transport);
1349 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1350 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1355 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1358 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1364 $failedRecipients = array();
1366 $result = $this->mailer->send($this->message, $failedRecipients);
1368 $this->errors[] = $e->getMessage();
1375 if (!empty($this->error) || !empty($this->errors) || !$result) {
1376 if (!empty($failedRecipients)) {
1377 $this->errors[] =
'Transport failed for the following addresses: "' . implode(
'", "', $failedRecipients) .
'".';
1379 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1386 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1392 $this->error =
'Bad value for sendmode';
1405 $parameters = array(
'sent' => $res);
1407 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1409 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1410 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1415 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1416 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1419 error_reporting($errorlevel);