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");
233 dol_syslog(
"CMailFile::CMailFile: subject=".$subject.
", deliveryreceipt=".$deliveryreceipt.
", msgishtml=".$msgishtml, LOG_DEBUG);
236 if (is_array($mimefilename_list)) {
237 foreach ($mimefilename_list as $key => $val) {
244 $this->sendcontext = $sendcontext;
247 $this->sendmode =
'';
248 if (!empty($this->sendcontext)) {
249 $smtpContextKey = strtoupper($this->sendcontext);
251 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
252 $this->sendmode = $smtpContextSendMode;
255 if (empty($this->sendmode)) {
265 $moreinheader .=
"Feedback-ID: ".$trackid.
':'.dol_getprefix(
'email').
":dolib\r\n";
271 $this->eol2 =
"\r\n";
275 $moreinheader = str_replace(
"\r\n",
"\n", $moreinheader);
279 $this->mixed_boundary =
"multipart_x.".time().
".x_boundary";
282 $this->related_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr2"),
'3');
285 $this->alternative_boundary =
'mul_'.dol_hash(uniqid(
"dolibarr3"),
'3');
287 if (empty($subject)) {
288 dol_syslog(
"CMailFile::CMailFile: Try to send an email with empty subject");
289 $this->error =
'ErrorSubjectIsRequired';
293 dol_syslog(
"CMailFile::CMailFile: Try to send an email with empty body");
298 if ($msgishtml == -1) {
299 $this->msgishtml = 0;
301 $this->msgishtml = 1;
304 $this->msgishtml = $msgishtml;
311 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT;
315 $msg = preg_replace(
'/src="'.preg_quote(DOL_URL_ROOT,
'/').
'\/viewimage\.php/ims',
'src="'.$urlwithroot.
'/viewimage.php', $msg, -1);
318 $this->msgishtml = 1;
320 dol_syslog(
"CMailFile::CMailFile: msgishtml=".$this->msgishtml, LOG_DEBUG);
323 if ($this->msgishtml) {
332 $dolibarr_main_data_root_images = $dolibarr_main_data_root;
333 if ((
int) $conf->entity !== 1) {
334 $dolibarr_main_data_root_images.=
'/'.$conf->entity.
'/';
336 $findimg = $this->
findHtmlImages($dolibarr_main_data_root_images.
'/medias');
338 dol_syslog(
"CMailFile::CMailFile: Error on findHtmlImages");
339 $this->error =
'ErrorInAddAttachmentsImageBaseOnMedia';
349 if ($resultImageData < 0) {
350 dol_syslog(
"CMailFile::CMailFile: Error on findHtmlImagesInSrcData code=".$resultImageData.
" upload_dir_tmp=".$upload_dir_tmp);
351 $this->error =
'ErrorInAddAttachmentsImageBaseIsSrcData';
354 $findimg += $resultImageData;
359 foreach ($this->html_images as $i => $val) {
360 if ($this->html_images[$i]) {
361 $this->atleastoneimage = 1;
362 if ($this->html_images[$i][
'type'] ==
'cidfromdata') {
363 if (!in_array($this->html_images[$i][
'fullpath'], $filename_list)) {
365 $posindice = count($filename_list);
366 $filename_list[$posindice] = $this->html_images[$i][
'fullpath'];
367 $mimetype_list[$posindice] = $this->html_images[$i][
'content_type'];
368 $mimefilename_list[$posindice] = $this->html_images[$i][
'name'];
370 $posindice = array_search($this->html_images[$i][
'fullpath'], $filename_list);
373 $cid_list[$posindice] = $this->html_images[$i][
'cid'];
375 dol_syslog(
"CMailFile::CMailFile: html_images[$i]['name']=".$this->html_images[$i][
'name'], LOG_DEBUG);
384 if (is_array($filename_list)) {
385 foreach ($filename_list as $i => $val) {
386 if ($filename_list[$i]) {
387 $this->atleastonefile = 1;
388 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);
397 foreach ($listofemailstoadd as $key => $val) {
398 $emailtoadd = $listofemailstoadd[$key];
399 if (trim($emailtoadd) ==
'__USER_EMAIL__') {
400 if (!empty($user) && !empty($user->email)) {
401 $emailtoadd = $user->email;
406 if ($emailtoadd && preg_match(
'/'.preg_quote($emailtoadd,
'/').
'/i', $to)) {
410 $listofemailstoadd[$key] = $emailtoadd;
412 unset($listofemailstoadd[$key]);
415 if (!empty($listofemailstoadd)) {
416 $addr_bcc .= ($addr_bcc ?
', ' :
'').implode(
', ', $listofemailstoadd);
423 $listofemailstonotsendto = explode(
',',
getDolGlobalString(
'MAIN_MAIL_FORCE_NOT_SENDING_TO'));
427 $tabto = explode(
",", $to);
428 foreach ($tabto as $key => $addrto) {
430 if (in_array($addrto[0], $listofemailstonotsendto)) {
438 $to = implode(
',', $tabto);
442 $tabcc = explode(
',', $addr_cc);
443 foreach ($tabcc as $key => $cc) {
445 if (in_array($cc[0], $listofemailstonotsendto)) {
453 $addr_cc = implode(
',', $tabcc);
457 $tabbcc = explode(
',', $addr_bcc);
458 foreach ($tabbcc as $key => $bcc) {
460 if (in_array($bcc[0], $listofemailstonotsendto)) {
461 unset($tabbcc[$key]);
468 $addr_bcc = implode(
',', $tabbcc);
472 if (empty($replyto)) {
480 $this->subject = $subject;
486 $this->deliveryreceipt = $deliveryreceipt;
489 $this->trackid = $trackid;
490 $this->in_reply_to = $in_reply_to;
491 $this->references = $references;
493 $this->filename_list = $filename_list;
494 $this->mimetype_list = $mimetype_list;
495 $this->mimefilename_list = $mimefilename_list;
496 $this->cid_list = $cid_list;
501 $this->addr_bcc =
'';
504 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
505 if (!empty($this->sendcontext)) {
506 $smtpContextKey = strtoupper($this->sendcontext);
508 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
509 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
513 dol_syslog(
"CMailFile::CMailFile: sendmode=".$this->sendmode.
" addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
517 if ($this->sendmode ==
'mail') {
528 if (!empty($moreinheader)) {
529 $smtp_headers .= $moreinheader;
535 if (!empty($this->html)) {
548 if (!empty($this->atleastonefile) && $filename_list !==
null && $mimetype_list !==
null && $mimefilename_list !==
null) {
549 $files_encoded = $this->
write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
553 $this->headers = $smtp_headers.$mime_headers;
556 $this->headers = preg_replace(
"/([\r\n]+)$/i",
"", $this->headers);
559 $this->message =
'This is a message with multiple parts in MIME format.'.$this->eol;
560 $this->message .= $text_body.$files_encoded;
561 $this->message .=
"--".$this->mixed_boundary.
"--".$this->eol;
562 } elseif ($this->sendmode ==
'smtps') {
565 $host = dol_getprefix(
'email');
567 require_once DOL_DOCUMENT_ROOT.
'/core/class/smtps.class.php';
568 $smtps =
new SMTPs();
569 $smtps->setCharSet($conf->file->character_set_client);
572 $subjecttouse = $this->subject;
577 $smtps->setSubject($subjecttouse);
582 $smtps->setTrackId($this->trackid);
584 if (!empty($this->in_reply_to)) {
585 $smtps->setInReplyTo($this->in_reply_to);
587 if (!empty($this->references)) {
588 $smtps->setReferences($this->references);
591 if (!empty($moreinheader)) {
592 $smtps->setMoreInHeader($moreinheader);
597 if (!empty($this->html)) {
610 $msg = preg_replace(
'/(\r|\n)\.(\r|\n)/ims',
'\1..\2', $msg);
612 if ($this->msgishtml) {
613 $smtps->setBodyContent($msg,
'html');
615 $smtps->setBodyContent($msg,
'plain');
618 if (!empty($this->atleastoneimage)) {
619 foreach ($this->images_encoded as $img) {
620 $smtps->setImageInline($img[
'image_encoded'], $img[
'name'], $img[
'content_type'], $img[
'cid']);
624 if (!empty($this->atleastonefile)) {
625 foreach ($filename_list as $i => $val) {
626 $content = file_get_contents($filename_list[$i]);
627 if (empty($cid_list[$i])) {
628 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], (empty($cid_list[$i]) ?
'' : $cid_list[$i]));
633 $smtps->setCC($this->addr_cc);
634 $smtps->setBCC($this->addr_bcc);
635 $smtps->setErrorsTo($this->errors_to);
636 $smtps->setDeliveryReceipt($this->deliveryreceipt);
640 $options = array(
'ssl' => array(
'verify_peer' =>
false,
'verify_peer_name' =>
false,
'allow_self_signed' =>
true));
643 $options = array_merge($options, array(
'ssl' => array(
'capture_peer_cert' =>
true,
'capture_peer_cert_chain' =>
true)));
653 $options = array_merge($options, array(
'socket' => [
'bindto' =>
'0.0.0.0:0']));
655 if (!empty($options)) {
656 $smtps->setOptions($options);
659 $this->msgid = uniqid(
'',
true).
'.SMTPs-dolibarr-'.$this->trackid.
'@'.$host;
661 $smtps->setMessageID($this->msgid);
663 $this->smtps = $smtps;
664 } elseif ($this->sendmode ==
'swiftmailer') {
667 $host = dol_getprefix(
'email');
669 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
672 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/autoload.php';
674 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
678 $this->message =
new Swift_Message();
681 $headers = $this->message->getHeaders();
683 $headers->addTextHeader(
'X-Dolibarr-TRACKID', $this->trackid.
'@'.$host);
684 $this->msgid = uniqid(
'',
true).
'.swiftmailer-dolibarr-'.$this->trackid.
'@'.$host;
685 $headerID = $this->msgid;
686 $msgid = $headers->get(
'Message-ID');
687 if ($msgid instanceof Swift_Mime_Headers_IdentificationHeader) {
688 $msgid->setId($headerID);
692 if (!empty($this->in_reply_to)) {
693 $headers->addIdHeader(
'In-Reply-To', $this->in_reply_to);
696 if (!empty($this->references)) {
697 $headers->addIdHeader(
'References', $this->references);
700 if (!empty($moreinheader)) {
701 $moreinheaderarray = preg_split(
'/[\r\n]+/', $moreinheader);
702 foreach ($moreinheaderarray as $moreinheaderval) {
703 $moreinheadervaltmp = explode(
':', $moreinheaderval, 2);
704 if (!empty($moreinheadervaltmp[0]) && !empty($moreinheadervaltmp[1])) {
705 $headers->addTextHeader($moreinheadervaltmp[0], $moreinheadervaltmp[1]);
712 $this->message->setSubject($this->subject);
714 $this->errors[] = $e->getMessage();
719 if (!empty($this->addr_from)) {
723 $regexp =
'/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
724 $adressEmailFrom = array();
725 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
726 $adressEmailFrom = reset($adressEmailFrom);
727 if ($emailMatchs !==
false && filter_var(
getDolGlobalString(
'MAIN_MAIL_SMTPS_ID'), FILTER_VALIDATE_EMAIL) &&
getDolGlobalString(
'MAIN_MAIL_SMTPS_ID') !== $adressEmailFrom[0]) {
736 $this->errors[] = $e->getMessage();
741 if (!empty($this->addr_to)) {
745 $this->errors[] = $e->getMessage();
749 if (!empty($this->reply_to)) {
753 $this->errors[] = $e->getMessage();
757 if (!empty($this->errors_to)) {
759 $headers->addMailboxHeader(
'Errors-To', $this->
getArrayAddress($this->errors_to));
761 $this->errors[] = $e->getMessage();
766 $this->message->setCharSet($conf->file->character_set_client);
768 $this->errors[] = $e->getMessage();
771 if (!empty($this->html)) {
780 if ($this->atleastoneimage) {
781 foreach ($this->html_images as $img) {
783 $attachment = Swift_Image::fromPath($img[
'fullpath']);
785 $imgcid = $this->message->embed($attachment);
787 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
789 foreach ($this->images_encoded as $img) {
791 $attachment = Swift_Image::fromPath($img[
'fullpath']);
793 $imgcid = $this->message->embed($attachment);
795 $msg = str_replace(
"cid:".$img[
'cid'], $imgcid, $msg);
799 if ($this->msgishtml) {
800 $this->message->setBody($msg,
'text/html');
802 $this->message->addPart(html_entity_decode(strip_tags($msg)),
'text/plain');
804 $this->message->setBody($msg,
'text/plain');
806 $this->message->addPart(
dol_nl2br($msg),
'text/html');
809 if (!empty($this->atleastonefile)) {
810 foreach ($filename_list as $i => $val) {
812 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
813 if (!empty($mimefilename_list[$i])) {
814 $attachment->setFilename($mimefilename_list[$i]);
816 $this->message->attach($attachment);
820 if (!empty($this->addr_cc)) {
824 $this->errors[] = $e->getMessage();
827 if (!empty($this->addr_bcc)) {
831 $this->errors[] = $e->getMessage();
834 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
836 $this->message->setReadReceiptTo($this->
getArrayAddress($this->addr_from));
838 $this->errors[] = $e->getMessage();
844 $this->error =
'Bad value for sendmode';
857 global $conf, $db, $langs, $hookmanager;
859 $errorlevel = error_reporting();
865 if (!is_object($hookmanager)) {
866 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
869 $hookmanager->initHooks(array(
'mail'));
871 $parameters = array();
873 $reshook = $hookmanager->executeHooks(
'sendMail', $parameters, $this, $action);
875 $this->error =
"Error in hook maildao sendMail ".$reshook;
876 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
881 dol_syslog(
"A hook has replaced code to send email", LOG_DEBUG);
885 $sendingmode = $this->sendmode;
886 if ($this->sendcontext ==
'emailing' &&
getDolGlobalString(
'MAILING_NO_USING_PHPMAIL') && $sendingmode ==
'mail') {
888 $listofmethods = array();
889 $listofmethods[
'mail'] =
'PHP mail function';
891 $listofmethods[
'smtps'] =
'SMTP/SMTPS socket library';
895 $linktoadminemailbefore =
'<a href="'.DOL_URL_ROOT.
'/admin/mails.php">';
896 $linktoadminemailend =
'</a>';
897 $this->error = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
898 $this->errors[] = $langs->trans(
"MailSendSetupIs", $listofmethods[$sendingmode]);
899 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
900 $this->errors[] = $langs->trans(
"MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv(
"MAIN_MAIL_SENDMODE"), $listofmethods[
'smtps']);
902 $this->error .=
'<br>'.$langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
903 $this->errors[] = $langs->trans(
"MailSendSetupIs3",
getDolGlobalString(
'MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
906 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
912 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
914 $tmparray1 = explode(
',', $this->addr_to);
915 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
916 $this->error =
'Too much recipients in to:';
917 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
921 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
923 $tmparray2 = explode(
',', $this->addr_cc);
924 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
925 $this->error =
'Too much recipients in cc:';
926 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
930 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
932 $tmparray3 = explode(
',', $this->addr_bcc);
933 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
934 $this->error =
'Too much recipients in bcc:';
935 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
939 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
941 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
942 $this->error =
'Too much recipients in to:, cc:, bcc:';
943 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
947 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER';
948 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT';
949 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID';
950 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW';
951 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE';
952 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
953 $keyfortls =
'MAIN_MAIL_EMAIL_TLS';
954 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS';
955 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
956 if (!empty($this->sendcontext)) {
957 $smtpContextKey = strtoupper($this->sendcontext);
959 if (!empty($smtpContextSendMode) && $smtpContextSendMode !=
'default') {
960 $keyforsmtpserver =
'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
961 $keyforsmtpport =
'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
962 $keyforsmtpid =
'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
963 $keyforsmtppw =
'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
964 $keyforsmtpauthtype =
'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
965 $keyforsmtpoauthservice =
'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
966 $keyfortls =
'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
967 $keyforstarttls =
'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
968 $keyforsslseflsigned =
'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
973 if ($this->sendmode ==
'mail') {
976 dol_syslog(
"CMailFile::sendfile addr_to=".$this->addr_to.
", subject=".$this->subject, LOG_NOTICE);
981 if (isset($_SERVER[
"WINDIR"])) {
982 if (empty($this->addr_from)) {
983 $this->addr_from =
'robot@example.com';
985 @ini_set(
'sendmail_from', $this->
getValidAddress($this->addr_from, 2));
998 if ($res && !$this->subject) {
999 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Subject is empty";
1000 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1004 if ($res && !$dest) {
1005 $this->error =
"Failed to send mail with php mail to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port').
"<br>Recipient address '$dest' invalid";
1006 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1011 $additionnalparam =
'';
1018 $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) :
''));
1021 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-ba';
1025 $additionnalparam .= ($additionnalparam ?
' ' :
'').
'-U '.$additionnalparam;
1029 if (preg_match(
'/^win/i', PHP_OS)) {
1032 if (preg_match(
'/^mac/i', PHP_OS)) {
1036 dol_syslog(
"CMailFile::sendfile: mail start".($linuxlike ?
'' :
" HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port')).
", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
1038 $this->message = stripslashes($this->message);
1045 $subjecttouse = $this->subject;
1050 if (!empty($additionnalparam)) {
1051 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
1053 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
1057 $langs->load(
"errors");
1058 $this->error =
"Failed to send mail with php mail";
1060 $this->error .=
" to HOST=".ini_get(
'SMTP').
", PORT=".ini_get(
'smtp_port');
1062 $this->error .=
".<br>";
1063 $this->error .= $langs->trans(
"ErrorPhpMailDelivery");
1064 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1070 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1074 if (isset($_SERVER[
"WINDIR"])) {
1075 @ini_restore(
'sendmail_from');
1080 ini_restore(
'SMTP');
1083 ini_restore(
'smtp_port');
1085 } elseif ($this->sendmode ==
'smtps') {
1086 if (!is_object($this->smtps)) {
1087 $this->error =
"Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1088 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1094 $this->smtps->setTransportType(0);
1097 if (empty($conf->global->$keyforsmtpserver)) {
1098 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1100 if (empty($conf->global->$keyforsmtpport)) {
1101 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1113 $server = ($secure ? $secure.
'://' :
'').$server;
1117 $this->smtps->setHost($server);
1118 $this->smtps->setPort($port);
1124 $this->smtps->setID($loginid);
1128 $this->smtps->setPW($loginpass);
1132 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1137 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1138 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1140 $keyforprovider =
'';
1142 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1143 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1145 if (!empty($supportedoauth2array)) {
1146 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1147 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1148 $OAUTH_SERVICENAME = $nameofservice;
1150 $OAUTH_SERVICENAME =
'Unknown';
1153 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1155 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1157 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1159 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1163 if (is_object($tokenobj)) {
1164 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1167 if (is_object($tokenobj) && $expire) {
1168 $credentials =
new Credentials(
1173 $serviceFactory = new \OAuth\ServiceFactory();
1174 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1177 $oauthScopes = array();
1179 if (!empty($oauthScopesStr)) {
1180 $oauthScopes = preg_split(
'/\s*,\s*/', $oauthScopesStr);
1181 if (!is_array($oauthScopes)) {
1182 $oauthScopes = array();
1187 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $oauthScopes);
1191 $refreshtoken = $tokenobj->getRefreshToken();
1193 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1195 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1196 if (empty($tokenobj->getRefreshToken())) {
1197 $tokenobj->setRefreshToken($refreshtoken);
1199 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1202 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1205 if (is_object($tokenobj)) {
1206 $this->smtps->setToken($tokenobj->getAccessToken());
1208 $this->error =
"Token not found";
1212 $this->error = $e->getMessage();
1213 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1218 $from = $this->smtps->getFrom(
'org');
1219 if ($res && !$from) {
1220 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Sender address '$from' invalid";
1221 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1224 $dest = $this->smtps->getTo();
1225 if ($res && !$dest) {
1226 $this->error =
"Failed to send mail with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - Recipient address '$dest' invalid";
1227 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1235 $this->smtps->setDebug(
true);
1238 $result = $this->smtps->sendMsg();
1246 $smtperrorcode = $this->smtps->lastretval;
1247 dol_syslog(
"CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1249 if ($smtperrorcode ==
'421') {
1263 dol_syslog(
"CMailFile::sendfile: mail SMTP sendMsg is success", LOG_DEBUG);
1266 $result = $this->smtps->getErrors();
1268 if (empty($this->error) && empty($result)) {
1269 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1272 if (empty($this->error)) {
1273 $this->error = $result;
1275 dol_syslog(
"CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.
", PORT=" .
getDolGlobalString($keyforsmtpport).
" - ".$this->error, LOG_ERR);
1279 $this->
save_dump_mail_in_err(
'Mail smtp error '.$smtperrorcode.
' with topic '.$this->subject.
' - '.$this->error);
1283 } elseif ($this->sendmode ==
'swiftmailer') {
1286 require_once DOL_DOCUMENT_ROOT.
'/includes/swiftmailer/lib/swift_required.php';
1289 if (empty($conf->global->$keyforsmtpserver)) {
1290 $conf->global->$keyforsmtpserver = ini_get(
'SMTP');
1292 if (empty($conf->global->$keyforsmtpport)) {
1293 $conf->global->$keyforsmtpport = ini_get(
'smtp_port');
1306 $this->transport =
new Swift_SmtpTransport($server,
getDolGlobalInt($keyforsmtpport), $secure);
1315 $this->transport->setAuthMode(
'XOAUTH2');
1316 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1321 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1322 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1324 $keyforprovider =
'';
1326 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1327 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1329 if (!empty($supportedoauth2array)) {
1330 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1331 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1332 $OAUTH_SERVICENAME = $nameofservice;
1334 $OAUTH_SERVICENAME =
'Unknown';
1337 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1339 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1341 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1344 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1348 if (is_object($tokenobj)) {
1349 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1352 if (is_object($tokenobj) && $expire) {
1353 $credentials =
new Credentials(
1358 $serviceFactory = new \OAuth\ServiceFactory();
1359 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1362 $oauthScopes = array();
1364 if (!empty($oauthScopesStr)) {
1365 $oauthScopes = preg_split(
'/\s*,\s*/', $oauthScopesStr);
1366 if (!is_array($oauthScopes)) {
1367 $oauthScopes = array();
1372 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $oauthScopes);
1373 $refreshtoken = $tokenobj->getRefreshToken();
1375 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1377 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1378 if (empty($tokenobj->getRefreshToken())) {
1379 $tokenobj->setRefreshToken($refreshtoken);
1381 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1383 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1387 if (is_object($tokenobj)) {
1388 $this->transport->setAuthMode(
'XOAUTH2');
1389 $this->transport->setPassword($tokenobj->getAccessToken());
1391 $this->errors[] =
"Token not found";
1392 dol_syslog(
"CMailFile::sendfile: OAuth2 token object is not valid", LOG_ERR);
1396 $this->errors[] = $e->getMessage();
1397 dol_syslog(
"CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1401 $this->transport->setStreamOptions(array(
'ssl' => array(
'allow_self_signed' =>
true,
'verify_peer' =>
false)));
1406 $contentEncoderBase64 =
new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1407 $this->message->setEncoder($contentEncoderBase64);
1410 $this->mailer =
new Swift_Mailer($this->transport);
1417 $signer =
new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1418 $this->message->attachSigner($signer->ignoreHeader(
'Return-Path'));
1423 $this->logger =
new Swift_Plugins_Loggers_ArrayLogger();
1426 $this->mailer->registerPlugin(
new Swift_Plugins_LoggerPlugin($this->logger));
1432 $failedRecipients = array();
1434 $result = $this->mailer->send($this->message, $failedRecipients);
1436 $this->errors[] = $e->getMessage();
1443 if (!empty($this->error) || !empty($this->errors) || !$result) {
1444 if (!empty($failedRecipients)) {
1445 $this->error =
'Transport failed for the following addresses: "' . implode(
'", "', $failedRecipients) .
'".';
1446 $this->errors[] = $this->error;
1448 dol_syslog(
"CMailFile::sendfile: mail end error=". implode(
' ', $this->errors), LOG_ERR);
1455 dol_syslog(
"CMailFile::sendfile: mail end success", LOG_DEBUG);
1461 $this->error =
'Bad value for sendmode';
1474 $parameters = array(
'sent' => $res);
1476 $reshook = $hookmanager->executeHooks(
'sendMailAfter', $parameters, $this, $action);
1478 $this->error =
"Error in hook maildao sendMailAfter ".$reshook;
1479 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1484 $this->error =
'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1485 dol_syslog(
"CMailFile::sendfile: ".$this->error, LOG_WARNING);
1488 error_reporting($errorlevel);