dolibarr 25.0.0-alpha
smtps.class.php
Go to the documentation of this file.
1<?php
2/*
3 * Copyright (C) Walter Torres <walter@torres.ws> [with a *lot* of help!]
4 * Copyright (C) 2005-2015 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2006-2011 Regis Houssin
6 * Copyright (C) 2016 Jonathan TISSEAU <jonathan.tisseau@86dev.fr>
7 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
48class SMTPs
49{
53 private $_smtpsHost = 'localhost';
54
61 private $_smtpsPort = 25;
62
67 private $_smtpsID = null;
68
73 private $_smtpsPW = null;
74
78 private $_smtpsToken = null;
79
83 private $_msgId = null;
84
88 private $_smtpsAuthType = '';
89
94 private $_msgFrom = null;
95
100 private $_msgReplyTo = null;
101
105 private $_msgInReplyTo = null;
106
110 private $_msgReferences = null;
111
117 private $_msgRecipients = null;
118
122 private $_msgSubject = null;
123
129 private $_msgContent = array();
130
134 private $_msgXheader = array();
135
141 private $_smtpsCharSet = 'iso-8859-1';
142
148 private $_msgSensitivity = 0;
149
153 private $_arySensitivity = array(false,
154 'Personal',
155 'Private',
156 'Company Confidential');
157
162 private $_msgPriority = 3;
163
167 private $_aryPriority = array('Bulk',
168 'Highest',
169 'High',
170 'Normal',
171 'Low',
172 'Lowest');
173
178 private $_smtpsTransEncodeType = 0;
179
183 private $_smtpsTransEncodeTypes = array('7bit', // Simple 7-bit ASCII
184 '8bit', // 8-bit coding with line termination characters
185 'base64', // 3 octets encoded into 4 sextets with offset
186 'binary', // Arbitrary binary stream
187 'mac-binhex40', // Macintosh binary to hex encoding
188 'quoted-printable', // Mostly 7-bit, with 8-bit characters encoded as "=HH"
189 'uuencode'); // UUENCODE encoding
190
196 private $_smtpsTransEncode = '7bit';
197
201 private $_smtpsBoundary = null;
202
206 private $_smtpsRelatedBoundary = null;
207
211 private $_smtpsAlternativeBoundary = null;
212
221 private $_transportType = 0;
222
227 private $_mailPath = '/usr/lib/sendmail'; // @phpstan-ignore-line
228
232 private $_smtpTimeout = 10;
233
237 private $_smtpMD5 = false;
238
242 private $_smtpsErrors = array();
243
251 private $_log_level = 0; // @phpstan-ignore-line
252
256 private $_debug = false;
257
258
259 // @CHANGE LDR
263 public $log = '';
267 public $lastretval = '';
268
272 public $socket;
273
277 public $errno;
278
282 public $errstr;
283
287 private $_errorsTo = array();
291 private $_deliveryReceipt = 0;
295 private $_trackId = '';
299 private $_moreinheader = '';
300
304 private $_options = array();
305
306
313 public function setMessageID($_msgId = '')
314 {
315 $this->_msgId = $_msgId;
316 }
317
324 public function setOptions($_options = array())
325 {
326 $this->_options = $_options;
327 }
328
335 public function setDeliveryReceipt($_val = 0)
336 {
337 $this->_deliveryReceipt = $_val;
338 }
339
345 public function getDeliveryReceipt()
346 {
347 return $this->_deliveryReceipt;
348 }
349
356 public function setSMTPTimeout($timeout)
357 {
358 $this->_smtpTimeout = $timeout;
359 }
360
366 public function getSMTPTimeout()
367 {
368 return $this->_smtpTimeout;
369 }
370
377 public function setTrackId($_val = '')
378 {
379 $this->_trackId = $_val;
380 }
381
388 public function setMoreInHeader($_val = '')
389 {
390 $this->_moreinheader = $_val;
391 }
392
398 public function getTrackId()
399 {
400 return $this->_trackId;
401 }
402
408 public function getMoreInHeader()
409 {
410 return $this->_moreinheader;
411 }
412
419 public function setErrorsTo($_strErrorsTo)
420 {
421 if ($_strErrorsTo) {
422 $this->_errorsTo = $this->_strip_email($_strErrorsTo);
423 }
424 }
425
432 public function getErrorsTo($_part = true)
433 {
434 $_retValue = '';
435
436 if ($_part === true || !array_key_exists($_part, $this->_errorsTo)) {
437 $_retValue = $this->_errorsTo;
438 } else {
439 $_retValue = $this->_errorsTo[$_part];
440 }
441
442 return $_retValue;
443 }
444
451 public function setDebug($_vDebug = false)
452 {
453 $this->_debug = $_vDebug;
454 }
455
461 public function buildRCPTlist()
462 {
463 // Pull TO list
464 $_aryToList = $this->getTo();
465 }
466
467 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
473 private function _server_connect()
474 {
475 // phpcs:enable
476 // Default return value
477 $_retVal = true;
478
479 // We have to make sure the HOST given is valid
480 // This is done here because '@fsockopen' will not give me this
481 // information if it fails to connect because it can't find the HOST
482 $host = $this->getHost();
483 $usetls = preg_match('@tls://@i', $host);
484
485 $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
486 $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
487 $host = preg_replace('@tls://@i', '', $host); // Remove prefix
488
489 // @CHANGE LDR
490 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
491
492 if ((!is_ip($host)) && ((gethostbyname($host)) == $host)) {
493 $this->_setErr(99, $host.' is either offline or is an invalid host name.');
494 $_retVal = false;
495 } else {
496 if (function_exists('stream_socket_client') && !empty($this->_options)) {
497 $socket_context = stream_context_create($this->_options); // An array of options for stream_context_create()
498 $this->socket = @stream_socket_client(
499 preg_replace('@tls://@i', '', $this->getHost()).// Host to 'hit', IP or domain
500 ':'.$this->getPort(), // which Port number to use
501 $this->errno, // actual system level error
502 $this->errstr, // and any text that goes with the error
503 $this->_smtpTimeout, // timeout for reading/writing data over the socket
504 STREAM_CLIENT_CONNECT,
505 $socket_context // Options for connection
506 );
507 } else {
508 $this->socket = @fsockopen(
509 preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain
510 $this->getPort(), // which Port number to use
511 $this->errno, // actual system level error
512 $this->errstr, // and any text that goes with the error
513 $this->_smtpTimeout // timeout for reading/writing data over the socket
514 );
515 }
516
517 //See if we can connect to the SMTP server
518 if (is_resource($this->socket)) {
519 // Fix from PHP SMTP class by 'Chris Ryan'
520 // Sometimes the SMTP server takes a little longer to respond
521 // so we will give it a longer timeout for the first read
522 // Windows still does not have support for this timeout function
523 if (function_exists('stream_set_timeout')) {
524 stream_set_timeout($this->socket, $this->_smtpTimeout, 0);
525 }
526
527 // Check response from Server
528 if ($_retVal = $this->server_parse($this->socket, "220")) {
529 $_retVal = $this->socket;
530 }
531 } else {
532 // This connection attempt failed.
533 // @CHANGE LDR
534 if (empty($this->errstr)) {
535 $this->errstr = 'Failed to connect with stream_context_create or fsockopen host='.$this->getHost().' port='.$this->getPort();
536 }
537 $this->_setErr($this->errno, $this->errstr);
538 $_retVal = false;
539 }
540 }
541
542 return $_retVal;
543 }
544
545 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
552 private function _server_authenticate($withauth = true)
553 {
554 // phpcs:enable
555 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
556 // Send the RFC2554 specified EHLO.
557 // This improvement as provided by 'SirSir' to
558 // accommodate both SMTP AND ESMTP capable servers
559 $host = $this->getHost();
560 $usetls = preg_match('@tls://@i', $host);
561
562 $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
563 $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
564 $host = preg_replace('@tls://@i', '', $host); // Remove prefix
565
566 if ($usetls && getDolGlobalString('MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO')) {
567 $host = 'tls://'.$host;
568 }
569
570 $hosth = $host; // so for example 'localhost' or 'smtp-relay.gmail.com'
571
572 if (getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO')) { // Note that default value is forced to MAIL_SMTP_USE_FROM_FOR_HELO=2 if not set
573 if (!is_numeric(getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO'))) {
574 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is a string, we use it as domain name
575 $hosth = getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO');
576 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 1) {
577 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 1, we use the domain in the from.
578 // So if the from to is 'aaa <bbb@ccc.com>', we will keep 'ccc.com'
579 $hosth = (string) $this->getFrom('addr');
580 $hosth = preg_replace('/^.*</', '', $hosth);
581 $hosth = preg_replace('/>.*$/', '', $hosth);
582 $hosth = preg_replace('/.*@/', '', $hosth);
583 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 2) {
584 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 2, we use the domain in the $dolibarr_main_url_root.
587 }
588 }
589
590 if ($_retVal = $this->socket_send_str('EHLO '.$hosth, '250')) {
591 if ($usetls) {
592 /*
593 The following dialog illustrates how a client and server can start a TLS STARTTLS session:
594 S: <waits for connection on TCP port 25>
595 C: <opens connection>
596 S: 220 mail.imc.org SMTP service ready
597 C: EHLO mail.ietf.org
598 S: 250-mail.imc.org offers a warm hug of welcome
599 S: 250 STARTTLS
600 C: STARTTLS
601 S: 220 Go ahead
602 C: <starts TLS negotiation>
603 C & S: <negotiate a TLS session>
604 C & S: <check result of negotiation>
605 // Second pass EHLO
606 C: EHLO client-domain.com
607 S: 250-server-domain.com
608 S: 250 AUTH LOGIN
609 C: <continues by sending an SMTP command
610
611 Another example here:
612 S: 220 smtp.server.com Simple Mail Transfer Service Ready
613 C: EHLO client.example.com
614 S: 250-smtp.server.com Hello client.example.com
615 S: 250-SIZE 1000000
616 S: 250-AUTH LOGIN PLAIN CRAM-MD5
617 S: 250-STARTTLS
618 S: 250 HELP
619 C: STARTTLS
620 S: 220 TLS go ahead
621 C: EHLO client.example.com *
622 S: 250-smtp.server.com Hello client.example.com
623 S: 250-SIZE 1000000
624 S: 250-AUTH LOGIN PLAIN CRAM-MD5
625 S: 250 HELP
626 C: AUTH LOGIN
627 S: 334 VXNlcm5hbWU6
628 C: adlxdkej
629 S: 334 UGFzc3dvcmQ6
630 C: lkujsefxlj
631 S: 235 2.7.0 Authentication successful
632 C: MAIL FROM:<mail@samlogic.com>
633 S: 250 OK
634 C: RCPT TO:<john@mail.com>
635 S: 250 OK
636 C: DATA
637 S: 354 Send message, end with a "." on a line by itself
638 C: <The message data (body text, subject, e-mail header, attachments etc) is sent>
639 S .
640 S: 250 OK, message accepted for delivery: queued as 12345
641 C: QUIT
642 S: 221 Bye
643 */
644 if (!$_retVal = $this->socket_send_str('STARTTLS', '220')) {
645 $this->_setErr(131, 'STARTTLS connection is not supported.');
646 return $_retVal;
647 }
648
649 // Before 5.6.7:
650 // STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_SSLv2_CLIENT|STREAM_CRYPTO_METHOD_SSLv3_CLIENT
651 // STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
652 // PHP >= 5.6.7:
653 // STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
654 // STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
655
656 $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
657 if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
658 $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
659 $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
660 }
661
662 if (!stream_socket_enable_crypto($this->socket, true, $crypto_method)) {
663 $this->_setErr(132, 'STARTTLS connection failed.');
664 return false;
665 }
666 // Most servers expect a 2nd pass of EHLO after TLS is established to get another time
667 // the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS.
668 if (! $_retVal = $this->socket_send_str('EHLO '.$hosth, '250')) {
669 $this->_setErr(126, '"'.$hosth.'" does not support authenticated connections or temporary error. Error after 2nd sending EHLO '.$hosth.' : '.$this->lastretval);
670 return $_retVal;
671 }
672 }
673
674 if (!$withauth) {
675 // No login, only EHLO and STARTTLS were needed
676 return $_retVal;
677 }
678
679 // Default authentication method is LOGIN
680 // Authentication method of the send context, else of the main setup
681 $authtype = $this->_smtpsAuthType ? $this->_smtpsAuthType : getDolGlobalString('MAIN_MAIL_SMTPS_AUTH_TYPE', 'LOGIN');
682
683 // Send Authentication to Server
684 // Check for errors along the way
685 switch ($authtype) {
686 case 'NONE':
687 // Do not send the 'AUTH type' message. For test purpose, if you don't need authentication, it is better to not enter login/pass into setup.
688 $_retVal = true;
689 break;
690 case 'PLAIN':
691 $_retVal = $this->socket_send_str('AUTH PLAIN', '334');
692 if (!$_retVal) {
693 // The login and password must not be sent if the server does not wait for them
694 $this->_setErr(130, 'Error when asking for AUTH PLAIN');
695 } else {
696 // The error here just means the ID/password combo doesn't work.
697 $_retVal = $this->socket_send_str(base64_encode("\0".$this->_smtpsID."\0".$this->_smtpsPW), '235');
698 }
699 break;
700 case 'XOAUTH2':
701 // "user=$email\1auth=Bearer $token\1\1"
702 $user = $this->_smtpsID;
703 $token = $this->_smtpsToken;
704 $initRes = "user=".$user."\001auth=Bearer ".$token."\001\001";
705 $_retVal = $this->socket_send_str('AUTH XOAUTH2 '.base64_encode($initRes), '235');
706 if (!$_retVal) {
707 $this->_setErr(130, 'Error when asking for AUTH XOAUTH2');
708 }
709 break;
710 case 'LOGIN': // most common case
711 default:
712 $_retVal = $this->socket_send_str('AUTH LOGIN', '334');
713 if (!$_retVal) {
714 $this->_setErr(130, 'Error when asking for AUTH LOGIN');
715 } else {
716 // User name will not return any error, server will take anything we give it.
717 $this->socket_send_str(base64_encode((string) $this->_smtpsID), '334');
718 // The error here just means the ID/password combo doesn't work.
719 // There is no method to determine which is the problem, ID or password
720 $_retVal = $this->socket_send_str(base64_encode((string) $this->_smtpsPW), '235');
721 }
722 break;
723 }
724 if (!$_retVal) {
725 $this->_setErr(130, 'Invalid Authentication Credentials.');
726 }
727 } else {
728 $this->_setErr(126, '"'.$host.'" refused the EHLO command. Error after sending EHLO '.$hosth.' : '.$this->lastretval);
729 }
730
731 return $_retVal;
732 }
733
739 public function sendMsg()
740 {
741 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
742
743 // Default return value
744 $_retVal = false;
745
746 // Connect to Server
747 if ($this->socket = $this->_server_connect()) {
748 // If a User ID *and* a password is given, assume Authentication is desired
749 if (!empty($this->_smtpsID) && (!empty($this->_smtpsPW) || !empty($this->_smtpsToken))) {
750 // Send the RFC2554 specified EHLO.
751 $_retVal = $this->_server_authenticate();
752 } elseif (preg_match('@tls://@i', $this->getHost())) {
753 // No login but STARTTLS is on: the switch to TLS is needed before sending the message, or it is sent in clear text
754 $_retVal = $this->_server_authenticate(false);
755 } else {
756 // This is a "normal" SMTP Server "handshack"
757 // Send the RFC821 specified HELO.
758 $host = $this->getHost();
759 $usetls = preg_match('@tls://@i', $host);
760
761 $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
762 $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
763 $host = preg_replace('@tls://@i', '', $host); // Remove prefix
764
765 if ($usetls && getDolGlobalString('MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO')) {
766 $host = 'tls://'.$host;
767 }
768
769 $hosth = $host;
770
771 if (getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO')) {
772 if (!is_numeric(getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO'))) {
773 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is a string, we use it as domain name
774 $hosth = getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO');
775 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 1) {
776 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 1, we use the domain in the from.
777 // So if the from to is 'aaa <bbb@ccc.com>', we will keep 'ccc.com'
778 $hosth = (string) $this->getFrom('addr');
779 $hosth = preg_replace('/^.*</', '', $hosth);
780 $hosth = preg_replace('/>.*$/', '', $hosth);
781 $hosth = preg_replace('/.*@/', '', $hosth);
782 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 2) {
783 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 2, we use the domain in the $dolibarr_main_url_root.
786 }
787 }
788
789 // Send the HELO message to the SMTP server
790 $_retVal = $this->socket_send_str('HELO '.$hosth, '250');
791 }
792
793 // Well, did we get the server answer with correct code ?
794 if ($_retVal) {
795 // From this point onward most server response codes should be 250
796 // Specify who the mail is from....
797 // This has to be the raw email address, strip the "name" off
798 $resultmailfrom = $this->socket_send_str('MAIL FROM: '.$this->getFrom('addr'), '250');
799 if (!$resultmailfrom) {
800 fclose($this->socket);
801 return false;
802 }
803
804 // 'RCPT TO:' must be given a single address, so this has to loop
805 // through the list of addresses, regardless of TO, CC or BCC
806 // and send it out "single file"
807 foreach ($this->get_RCPT_list() as $_address) {
808 /* Note:
809 * BCC email addresses must be listed in the RCPT TO command list,
810 * but the BCC header should not be printed under the DATA command.
811 * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
812 */
813
814 /*
815 * If any address fails, the entire message fails: the sending is reported as failed, so sending
816 * the message to the other recipients would make duplicates when it is sent again.
817 * Closing the connection before the end of the data cancels the message.
818 */
819 if (!$this->socket_send_str('RCPT TO: <'.$_address.'>', '250')) {
820 fclose($this->socket);
821 return false;
822 }
823 }
824
825 // Tell the server we are ready to start sending data
826 // with any custom headers...
827 // This is the last response code we look for until the end of the message.
828 if (!$this->socket_send_str('DATA', '354')) {
829 // The data must not be sent, the server would read it as SMTP commands
830 fclose($this->socket);
831 return false;
832 }
833
834 // Now we are ready for the message...
835 // Ok, all the ingredients are mixed in let's cook this puppy...
836 $data = $this->getHeader().$this->getBodyContent();
837 // Dot-stuffing (RFC 5321 4.5.2): a line starting with a "." gets a second one, that the server removes.
838 // Without it, a line with only "." ends the data and the next lines are read by the server as SMTP commands.
839 $data = preg_replace('/^\./m', '..', $data);
840 $_retVal = $this->socket_send_str($data."\r\n".'.', '250');
841
842 // Now tell the server we are done and close the socket...
843 $this->socket_send_str('QUIT');
844 } else {
845 // We got error code into $this->lastretval
846 }
847
848 fclose($this->socket);
849 }
850
851 return $_retVal;
852 }
853
854 // =============================================================
855 // ** Setter & Getter methods
856
857 // ** Basic System configuration
858
884 public function setConfig($_strConfigPath = null)
885 {
890 $_retVal = true;
891
892 // if we have a path...
893 if (!empty($_strConfigPath)) {
894 // If the path is not valid, this will NOT generate an error,
895 // it will simply return false.
896 if (!@include $_strConfigPath) {
897 $this->_setErr(110, '"'.$_strConfigPath.'" is not a valid path.');
898 $_retVal = false;
899 }
900 } else {
901 // Read the Systems php.ini file
902 // Set these properties ONLY if they are set in the php.ini file.
903 // Otherwise the default values will be used.
904 if ($_host = ini_get('SMTPs')) {
905 $this->setHost($_host);
906 }
907
908 if ($_port = ini_get('smtp_port')) {
909 $this->setPort($_port);
910 }
911
912 if ($_from = ini_get('sendmail_from')) {
913 $this->setFrom($_from);
914 }
915 }
916
917 // Send back what we have
918 return $_retVal;
919 }
920
930 public function setTransportType($_type = 0)
931 {
932 if ((is_numeric($_type)) && (($_type >= 0) && ($_type <= 3))) {
933 $this->_transportType = $_type;
934 }
935 }
936
945 public function getTransportType()
946 {
947 return $this->_transportType;
948 }
949
956 public function setMailPath($_path)
957 {
958 // This feature is not yet implemented
959 return true;
960
961 //if ( $_path ) $this->_mailPath = $_path;
962 }
963
972 public function setHost($_strHost)
973 {
974 if ($_strHost) {
975 $this->_smtpsHost = $_strHost;
976 }
977 }
978
985 public function getHost()
986 {
987 return $this->_smtpsHost;
988 }
989
998 public function setPort($_intPort)
999 {
1000 if ((is_numeric($_intPort)) &&
1001 (($_intPort >= 1) && ($_intPort <= 65536))) {
1002 $this->_smtpsPort = (int) $_intPort;
1003 }
1004 }
1005
1012 public function getPort()
1013 {
1014 return (int) $this->_smtpsPort;
1015 }
1016
1023 public function setID($_strID)
1024 {
1025 $this->_smtpsID = $_strID;
1026 }
1027
1033 public function getID()
1034 {
1035 return $this->_smtpsID;
1036 }
1037
1044 public function setPW($_strPW)
1045 {
1046 $this->_smtpsPW = $_strPW;
1047 }
1048
1054 public function getPW()
1055 {
1056 return $this->_smtpsPW;
1057 }
1058
1065 public function setToken($_strToken)
1066 {
1067 $this->_smtpsToken = $_strToken;
1068 }
1069
1076 public function setAuthType($_strAuthType)
1077 {
1078 $this->_smtpsAuthType = (string) $_strAuthType;
1079 }
1080
1086 public function getToken()
1087 {
1088 return $this->_smtpsToken;
1089 }
1090
1098 public function setCharSet($_strCharSet)
1099 {
1100 if ($_strCharSet) {
1101 $this->_smtpsCharSet = $_strCharSet;
1102 }
1103 }
1104
1110 public function getCharSet()
1111 {
1112 return $this->_smtpsCharSet;
1113 }
1114
1130 public function setTransEncode($_strTransEncode)
1131 {
1132 if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes)) {
1133 $this->_smtpsTransEncode = $_strTransEncode;
1134 }
1135 }
1136
1142 public function getTransEncode()
1143 {
1144 return $this->_smtpsTransEncode;
1145 }
1146
1162 public function setTransEncodeType($_strTransEncodeType)
1163 {
1164 if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes)) {
1165 $this->_smtpsTransEncodeType = $_strTransEncodeType;
1166 }
1167 }
1168
1174 public function getTransEncodeType()
1175 {
1176 return $this->_smtpsTransEncodeTypes[$this->_smtpsTransEncodeType];
1177 }
1178
1179
1180 // ** Message Construction
1181
1188 public function setFrom($_strFrom)
1189 {
1190 if ($_strFrom) {
1191 $this->_msgFrom = $this->_strip_email($_strFrom);
1192 }
1193 }
1194
1201 public function getFrom($_part = true)
1202 {
1203 $_retValue = '';
1204
1205 if ($_part === true || $this->_msgFrom === null) {
1206 $_retValue = $this->_msgFrom;
1207 } else {
1208 $_retValue = $this->_msgFrom[$_part];
1209 }
1210
1211 return $_retValue;
1212 }
1213
1220 public function setReplyTo($_strReplyTo)
1221 {
1222 if ($_strReplyTo) {
1223 $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
1224 }
1225 }
1226
1233 public function getReplyTo($_part = true)
1234 {
1235 $_retValue = '';
1236
1237 if ($_part === true) {
1238 $_retValue = $this->_msgReplyTo;
1239 } else {
1240 $_retValue = $this->_msgReplyTo[$_part];
1241 }
1242
1243 return $_retValue;
1244 }
1245
1252 public function setInReplyTo($_strInReplyTo)
1253 {
1254 if ($_strInReplyTo) {
1255 $this->_msgInReplyTo = $_strInReplyTo;
1256 }
1257 }
1258
1264 public function getInReplyTo()
1265 {
1266 $_retValue = $this->_msgInReplyTo;
1267
1268 return $_retValue;
1269 }
1270
1277 public function setReferences($_strReferences)
1278 {
1279 if ($_strReferences) {
1280 $this->_msgReferences = $_strReferences;
1281 }
1282 }
1283
1289 public function getReferences()
1290 {
1291 $_retValue = $this->_msgReferences;
1292
1293 return $_retValue;
1294 }
1295
1305 private function _buildAddrList($_type, $_addrList)
1306 {
1307 // Pull existing list
1308 $aryHost = $this->_msgRecipients;
1309
1310 // Only run this if we have something
1311 if (!empty($_addrList)) {
1312 // $_addrList can be a STRING or an array
1313 if (is_string($_addrList)) {
1314 // This could be a COMMA delimited string
1315 if (strstr($_addrList, ',')) {
1316 // "explode "list" into an array
1317 $_addrList = explode(',', $_addrList);
1318 } else {
1319 // Stick it in an array
1320 $_addrList = array($_addrList);
1321 }
1322 }
1323
1324 // take the array of addresses and split them further
1325 foreach ($_addrList as $_strAddr) {
1326 // Strip off the end '>'
1327 $_strAddr = str_replace('>', '', $_strAddr);
1328
1329 // Separate "Real Name" from eMail address
1330 $_tmpaddr = null;
1331 $_tmpaddr = explode('<', $_strAddr);
1332
1333 // We have a "Real Name" and eMail address
1334 if (count($_tmpaddr) == 2) {
1335 $_tmpHost = explode('@', $_tmpaddr[1]);
1336 $_tmpaddr[0] = trim($_tmpaddr[0], ' ">');
1337 $aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = $_tmpaddr[0];
1338 } else {
1339 // We only have an eMail address
1340 // Strip off the beginning '<'
1341 $_strAddr = str_replace('<', '', $_strAddr);
1342
1343 $_tmpHost = explode('@', $_strAddr);
1344 $_tmpHost[0] = trim($_tmpHost[0]);
1345 $_tmpHost[1] = trim($_tmpHost[1]);
1346
1347 $aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = '';
1348 }
1349 }
1350 }
1351 // replace list
1352 $this->_msgRecipients = $aryHost;
1353 }
1354
1355 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1372 private function _strip_email($_strAddr)
1373 {
1374 // phpcs:enable
1375 $_aryEmail = array();
1376 // Keep the original
1377 $_aryEmail['org'] = $_strAddr;
1378
1379 // Set entire string to Lower Case
1380 $_strAddr = strtolower($_strAddr);
1381
1382 // Drop "stuff' off the end
1383 $_strAddr = trim($_strAddr, ' ">');
1384
1385 // Separate "Real Name" from eMail address, if we have one
1386 $_tmpAry = explode('<', $_strAddr);
1387
1388 // Do we have a "Real name"
1389 if (count($_tmpAry) == 2) {
1390 // We may not really have a "Real Name"
1391 if ($_tmpAry[0]) {
1392 $_aryEmail['real'] = trim($_tmpAry[0], ' ">');
1393 }
1394
1395 $_aryEmail['addr'] = $_tmpAry[1];
1396 } else {
1397 $_aryEmail['addr'] = $_tmpAry[0];
1398 }
1399
1400 // Pull User Name and Host.tld apart
1401 $_tmpHost = explode('@', $_aryEmail['addr']);
1402 $_aryEmail['user'] = $_tmpHost[0];
1403 $_aryEmail['host'] = $_tmpHost[1];
1404
1405 // Put the brackets back around the address
1406 $_aryEmail['addr'] = '<'.$_aryEmail['addr'].'>';
1407
1408 return $_aryEmail;
1409 }
1410
1411 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1419 public function get_RCPT_list()
1420 {
1421 // phpcs:enable
1425 $_RCPT_list = array();
1426
1427 // walk down Recipients array and pull just email addresses
1428 foreach ($this->_msgRecipients as $_host => $_list) {
1429 foreach ($_list as $_subList) {
1430 foreach ($_subList as $_name => $_addr) {
1431 // build RCPT list
1432 $_RCPT_list[] = $_name.'@'.$_host;
1433 }
1434 }
1435 }
1436
1437 return $_RCPT_list;
1438 }
1439
1440 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1447 public function get_email_list($_which = null)
1448 {
1449 // phpcs:enable
1450 // We need to know which address segment to pull
1451 if ($_which) {
1452 // Make sure we have addresses to process
1453 if ($this->_msgRecipients) {
1454 $_RCPT_list = array();
1455 // walk down Recipients array and pull just email addresses
1456 foreach ($this->_msgRecipients as $_host => $_list) {
1457 if (!empty($this->_msgRecipients[$_host][$_which])) {
1458 foreach ($this->_msgRecipients[$_host][$_which] as $_addr => $_realName) {
1459 if ($_realName) { // @CHANGE LDR
1460 $_realName = '"'.$_realName.'"';
1461 $_RCPT_list[] = $_realName.' <'.$_addr.'@'.$_host.'>';
1462 } else {
1463 $_RCPT_list[] = $_addr.'@'.$_host;
1464 }
1465 }
1466 }
1467 }
1468
1469 return implode(', ', $_RCPT_list);
1470 } else {
1471 $this->_setErr(101, 'No eMail Address for message to be sent to.');
1472 return false;
1473 }
1474 } else {
1475 $this->_setErr(102, 'eMail type not defined.');
1476 return false;
1477 }
1478 }
1479
1486 public function setTO($_addrTo)
1487 {
1488 if ($_addrTo) {
1489 $this->_buildAddrList('to', $_addrTo);
1490 }
1491 }
1492
1498 public function getTo()
1499 {
1500 return $this->get_email_list('to');
1501 }
1502
1509 public function setCC($_strCC)
1510 {
1511 if ($_strCC) {
1512 $this->_buildAddrList('cc', $_strCC);
1513 }
1514 }
1515
1521 public function getCC()
1522 {
1523 return $this->get_email_list('cc');
1524 }
1525
1532 public function setBCC($_strBCC)
1533 {
1534 if ($_strBCC) {
1535 $this->_buildAddrList('bcc', $_strBCC);
1536 }
1537 }
1538
1544 public function getBCC()
1545 {
1546 return $this->get_email_list('bcc');
1547 }
1548
1555 public function setSubject($_strSubject = '')
1556 {
1557 if ($_strSubject) {
1558 $this->_msgSubject = $_strSubject;
1559 }
1560 }
1561
1567 public function getSubject()
1568 {
1569 return $this->_msgSubject;
1570 }
1571
1577 public function getHeader()
1578 {
1579 $_header = 'From: '.$this->getFrom('org')."\r\n"
1580 . 'To: '.$this->getTo()."\r\n";
1581
1582 if ($this->getCC()) {
1583 $_header .= 'Cc: '.$this->getCC()."\r\n";
1584 }
1585
1586 /* Note:
1587 * BCC email addresses must be listed in the RCPT TO command list,
1588 * but the BCC header should not be printed under the DATA command.
1589 * So it is included into the function sendMsg() but not here.
1590 * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
1591 */
1592 /*
1593 if ( $this->getBCC() )
1594 $_header .= 'Bcc: ' . $this->getBCC() . "\r\n";
1595 */
1596
1597 $host = dol_getprefix('email');
1598
1599 $_header .= 'Subject: '.$this->getSubject()."\r\n";
1600 $_header .= 'Date: '.date("r")."\r\n";
1601
1602 $trackid = $this->getTrackId();
1603 if ($trackid) {
1604 $_header .= 'Message-ID: <'.(empty($this->_msgId) ? uniqid().'.SMTPs-dolibarr-'.$trackid.'@'.$host : $this->_msgId).">\r\n";
1605 $_header .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host."\r\n";
1606 } else {
1607 $_header .= 'Message-ID: <'.(empty($this->_msgId) ? uniqid().'.SMTPs@'.$host : $this->_msgId).">\r\n";
1608 }
1609 if (!empty($_SERVER['REMOTE_ADDR'])) {
1610 $_header .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR']."\r\n";
1611 }
1612 if ($this->getMoreInHeader()) {
1613 // Value must include the "\r\n". With MAIN_FIX_FOR_BUGGED_MTA, CMailFile gives "\n", but SMTP needs "\r\n"
1614 $_header .= preg_replace('/(?<!\r)\n/', "\r\n", $this->getMoreInHeader());
1615 }
1616
1617 if ($this->getSensitivity()) {
1618 $_header .= 'Sensitivity: '.$this->getSensitivity()."\r\n";
1619 }
1620
1621 if ($this->_msgPriority != 3) {
1622 $_header .= $this->getPriority();
1623 }
1624
1625
1626 // @CHANGE LDR
1627 if ($this->getDeliveryReceipt()) {
1628 $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr')."\r\n";
1629 }
1630 if ($this->getErrorsTo()) {
1631 $_header .= 'Errors-To: '.$this->getErrorsTo('addr')."\r\n";
1632 }
1633 if ($this->getReplyTo()) {
1634 $_header .= "Reply-To: ".$this->getReplyTo('addr')."\r\n";
1635 }
1636
1637 $_header .= 'X-Mailer: Dolibarr version '.DOL_VERSION.' (using SMTPs Mailer)'."\r\n";
1638 $_header .= 'X-Dolibarr-Option: '.(getDolGlobalString('MAIN_MAIL_USE_MULTI_PART') ? 'MAIN_MAIL_USE_MULTI_PART' : 'No MAIN_MAIL_USE_MULTI_PART')."\r\n";
1639 $_header .= 'Mime-Version: 1.0'."\r\n";
1640
1641 // Add also $this->references and In-Reply-To
1642 if ($this->getInReplyTo()) {
1643 $_header .= "In-Reply-To: ".$this->getInReplyTo()."\r\n";
1644 }
1645 $references = $this->getReferences();
1646 if ($references) {
1647 // List of message ids:
1648 // Example "References: <id1@domain2.com> <id2@domain.com>
1649 $_header .= "References: ".implode(' ', $references)."\r\n";
1650 }
1651
1652 return $_header;
1653 }
1654
1662 public function setBodyContent($strContent, $strType = 'plain')
1663 {
1664 //if ( $strContent )
1665 //{
1666 if ($strType == 'html') {
1667 $strMimeType = 'text/html';
1668 } else {
1669 $strMimeType = 'text/plain';
1670 }
1671
1672 // Make RFC821 Compliant, replace bare linefeeds
1673 $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $strContent);
1674
1675 $strContentAltText = '';
1676 if ($strType == 'html') {
1677 // Similar code to forge a text from html is also in CMailFile.class.php
1678 $strContentAltText = preg_replace('/<head><title>.*<\/style><\/head>/', '', $strContent);
1679 $strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContentAltText);
1680 $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1681 $strContentAltText = trim(wordwrap($strContentAltText, 75, "\r\n"));
1682 }
1683
1684 // Make RFC2045 Compliant
1685 //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content
1686 $strContent = rtrim(wordwrap($strContent, 75, "\r\n")); // TODO Using this method creates unexpected line break on text/plain content.
1687
1688 $this->_msgContent[$strType] = array();
1689
1690 $this->_msgContent[$strType]['mimeType'] = $strMimeType;
1691 $this->_msgContent[$strType]['data'] = $strContent;
1692 $this->_msgContent[$strType]['dataText'] = $strContentAltText;
1693
1694 if ($this->getMD5flag()) {
1695 $this->_msgContent[$strType]['md5'] = dol_hash($strContent, '3');
1696 }
1697 //}
1698 }
1699
1705 public function getBodyContent()
1706 {
1707 global $conf;
1708
1709 // Generate a new Boundary string
1710 $this->_setBoundary();
1711
1712 // What type[s] of content do we have
1713 $_types = array_keys($this->_msgContent);
1714
1715 // How many content types do we have
1716 $keyCount = count($_types);
1717
1718 // If we have ZERO, we have a problem
1719 if ($keyCount === 0) {
1720 die("Sorry, no content");
1721 } elseif ($keyCount === 1 && !getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1722 // If we have ONE, we can use the simple format
1723 $_msgData = $this->_msgContent;
1724 $_msgData = $_msgData[$_types[0]];
1725
1726 $content = 'Content-Type: '.$_msgData['mimeType'].'; charset="'.$this->getCharSet().'"'."\r\n"
1727 . 'Content-Transfer-Encoding: '.$this->_getTextTransferEncoding($_msgData['data'])."\r\n"
1728 . 'Content-Disposition: inline'."\r\n"
1729 . 'Content-Description: Message'."\r\n";
1730
1731 if ($this->getMD5flag()) {
1732 $content .= 'Content-MD5: '.$_msgData['md5']."\r\n";
1733 }
1734
1735 $content .= "\r\n"
1736 . $_msgData['data']."\r\n";
1737 } elseif ($keyCount >= 1 || getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1738 // If we have more than ONE, we use the multi-part format
1739 // Since this is an actual multi-part message
1740 // We need to define a content message Boundary
1741 // NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this.
1742
1743 //$content = 'Content-Type: multipart/related; boundary="' . $this->_getBoundary() . '"' . "\r\n";
1744 $content = 'Content-Type: multipart/mixed; boundary="'.$this->_getBoundary('mixed').'"'."\r\n";
1745
1746 // . "\r\n"
1747 // . 'This is a multi-part message in MIME format.' . "\r\n";
1748 $content .= "Content-Transfer-Encoding: 8bit\r\n";
1749 $content .= "\r\n";
1750
1751 $content .= "--".$this->_getBoundary('mixed')."\r\n";
1752
1753 if (array_key_exists('image', $this->_msgContent)) { // If inline image found
1754 $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
1755 $content .= "\r\n";
1756 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1757 }
1758
1759
1760 // $this->_msgContent must be sorted with key 'text' or 'html' first then 'image' then 'attachment'
1761
1762
1763 // Loop through message content array
1764 foreach ($this->_msgContent as $type => $_content) {
1765 if ($type == 'attachment') {
1766 // loop through all attachments
1767 foreach ($_content as $_file => $_data) {
1768 $content .= "--".$this->_getBoundary('mixed')."\r\n"
1769 . 'Content-Disposition: attachment; filename="'.$_data['fileName'].'"'."\r\n"
1770 . 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['fileName'].'"'."\r\n"
1771 . 'Content-Transfer-Encoding: base64'."\r\n"
1772 . 'Content-Description: '.$_data['fileName']."\r\n";
1773 if (!empty($_data['cid'])) {
1774 $content .= "X-Attachment-Id: ".$_data['cid']."\r\n";
1775 $content .= "Content-ID: <".$_data['cid'].">\r\n";
1776 }
1777 if ($this->getMD5flag()) {
1778 $content .= 'Content-MD5: '.$_data['md5']."\r\n";
1779 }
1780
1781 $content .= "\r\n".$_data['data']."\r\n\r\n";
1782 }
1783 } elseif ($type == 'image') {
1784 // @CHANGE LDR
1785 // loop through all images
1786 foreach ($_content as $_image => $_data) {
1787 $content .= "--".$this->_getBoundary('related')."\r\n"; // always related for an inline image
1788
1789 $content .= 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['imageName'].'"'."\r\n"
1790 . 'Content-Transfer-Encoding: base64'."\r\n"
1791 . 'Content-Disposition: inline; filename="'.$_data['imageName'].'"'."\r\n"
1792 . 'Content-ID: <'.$_data['cid'].'> '."\r\n";
1793
1794 if ($this->getMD5flag()) {
1795 $content .= 'Content-MD5: '.$_data['md5']."\r\n";
1796 }
1797
1798 $content .= "\r\n"
1799 . $_data['data']."\r\n";
1800 }
1801
1802 // always end related and end alternative after inline images
1803 $content .= "--".$this->_getBoundary('related')."--\r\n";
1804 $content .= "\r\n--".$this->_getBoundary('alternative')."--\r\n";
1805 $content .= "\r\n";
1806 } else {
1807 if (array_key_exists('image', $this->_msgContent)) {
1808 $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
1809 $content .= 'Content-Transfer-Encoding: '.$this->_getTextTransferEncoding($_content['dataText'] ? $_content['dataText'] : strip_tags($_content['data']))."\r\n";
1810 $content .= "\r\n".($_content['dataText'] ? $_content['dataText'] : strip_tags($_content['data']))."\r\n"; // Add plain text message
1811 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1812 $content .= 'Content-Type: multipart/related; boundary="'.$this->_getBoundary('related').'"'."\r\n";
1813 $content .= "\r\n";
1814 $content .= "--".$this->_getBoundary('related')."\r\n";
1815 }
1816
1817 if (!array_key_exists('image', $this->_msgContent) && $_content['dataText'] && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1818 // Add plain text message part before html part
1819 $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
1820 $content .= "\r\n";
1821 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1822
1823 $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
1824 $content .= 'Content-Transfer-Encoding: '.$this->_getTextTransferEncoding($_content['dataText'])."\r\n";
1825 $content .= "\r\n".$_content['dataText']."\r\n";
1826 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1827 }
1828
1829 $content .= 'Content-Type: '.$_content['mimeType'].'; charset='.$this->getCharSet();
1830
1831 $content .= "\r\n";
1832 $content .= 'Content-Transfer-Encoding: '.$this->_getTextTransferEncoding($_content['data'])."\r\n";
1833
1834 if ($this->getMD5flag()) {
1835 $content .= 'Content-MD5: '.$_content['md5']."\r\n";
1836 }
1837
1838 $content .= "\r\n".$_content['data']."\r\n";
1839
1840 if (!array_key_exists('image', $this->_msgContent) && $_content['dataText'] && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1841 // Add plain text message part after html part
1842 $content .= "--".$this->_getBoundary('alternative')."--\r\n";
1843 }
1844
1845 $content .= "\r\n";
1846 }
1847 }
1848
1849 $content .= "--".$this->_getBoundary('mixed').'--'."\r\n";
1850 } else {
1851 die("Sorry, no content");
1852 }
1853
1854 return $content;
1855 }
1856
1857 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1865 private function _getTextTransferEncoding($text)
1866 {
1867 // phpcs:enable
1868 if (preg_match('/[^\x00-\x7F]/', $text)) {
1869 return '8bit';
1870 }
1871 return $this->getTransEncodeType();
1872 }
1873
1884 public function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown', $strCid = '')
1885 {
1886 if ($strContent) {
1887 $strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n")); // 76 max is defined into http://tools.ietf.org/html/rfc2047
1888
1889 // The key is the file name and the hash of its content: the same file given twice is attached once, but 2 different
1890 // files with the same name (from different directories) are both attached.
1891 $attachmentkey = $strFileName.'-'.dol_hash($strContent, 'sha256');
1892
1893 $this->_msgContent['attachment'][$attachmentkey]['mimeType'] = $strMimeType;
1894 $this->_msgContent['attachment'][$attachmentkey]['fileName'] = $strFileName;
1895 $this->_msgContent['attachment'][$attachmentkey]['data'] = $strContent;
1896 $this->_msgContent['attachment'][$attachmentkey]['cid'] = $strCid; // If defined, it means this attachment must be shown inline
1897
1898 if ($this->getMD5flag()) {
1899 $this->_msgContent['attachment'][$attachmentkey]['md5'] = dol_hash($strContent, '3');
1900 }
1901 }
1902 }
1903
1904
1905 // @CHANGE LDR
1906
1917 public function setImageInline($strContent, $strImageName = 'unknown', $strMimeType = 'unknown', $strImageCid = 'unknown')
1918 {
1919 if ($strContent) {
1920 $this->_msgContent['image'][$strImageName]['mimeType'] = $strMimeType;
1921 $this->_msgContent['image'][$strImageName]['imageName'] = $strImageName;
1922 $this->_msgContent['image'][$strImageName]['data'] = $strContent;
1923 $this->_msgContent['image'][$strImageName]['cid'] = $strImageCid;
1924
1925 if ($this->getMD5flag()) {
1926 $this->_msgContent['image'][$strImageName]['md5'] = dol_hash($strContent, '3');
1927 }
1928 }
1929 }
1930 // END @CHANGE LDR
1931
1932
1944 public function setSensitivity($_value = 0)
1945 {
1946 if ((is_numeric($_value)) &&
1947 (($_value >= 0) && ($_value <= 3))) {
1948 $this->_msgSensitivity = $_value;
1949 }
1950 }
1951
1962 public function getSensitivity()
1963 {
1964 return $this->_arySensitivity[$this->_msgSensitivity];
1965 }
1966
1980 public function setPriority($_value = 3)
1981 {
1982 if ((is_numeric($_value)) &&
1983 (($_value >= 0) && ($_value <= 5))) {
1984 $this->_msgPriority = $_value;
1985 }
1986 }
1987
2000 public function getPriority()
2001 {
2002 return 'Importance: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
2003 . 'Priority: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
2004 . 'X-Priority: '.$this->_msgPriority.' ('.$this->_aryPriority[$this->_msgPriority].')'."\r\n";
2005 }
2006
2013 public function setMD5flag($_flag = false)
2014 {
2015 $this->_smtpMD5 = $_flag;
2016 }
2017
2023 public function getMD5flag()
2024 {
2025 return $this->_smtpMD5;
2026 }
2027
2036 public function setXheader($strXdata)
2037 {
2038 if ($strXdata) {
2039 $this->_msgXheader[] = $strXdata;
2040 }
2041 }
2042
2048 public function getXheader()
2049 {
2050 return $this->_msgXheader;
2051 }
2052
2058 private function _setBoundary()
2059 {
2060 $this->_smtpsBoundary = "multipart_x.".time().".x_boundary";
2061 $this->_smtpsRelatedBoundary = 'mul_'.dol_hash(uniqid("dolibarr2"), '3');
2062 $this->_smtpsAlternativeBoundary = 'mul_'.dol_hash(uniqid("dolibarr3"), '3');
2063 }
2064
2071 private function _getBoundary($type = 'mixed')
2072 {
2073 if ($type == 'mixed') {
2074 return $this->_smtpsBoundary;
2075 } elseif ($type == 'related') {
2076 return $this->_smtpsRelatedBoundary;
2077 } elseif ($type == 'alternative') {
2078 return $this->_smtpsAlternativeBoundary;
2079 }
2080 return '';
2081 }
2082
2083 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2094 public function server_parse($socket, $response)
2095 {
2096 // phpcs:enable
2101 $_retVal = true;
2102
2103 $server_response = '';
2104
2105 // avoid infinite loop
2106 $limit = 0;
2107
2108 while (substr($server_response, 3, 1) != ' ' && $limit < 100) {
2109 // Read the whole line (a reply line longer than the read size would be read as 2 replies)
2110 if (!($server_response = fgets($socket))) {
2111 $this->_setErr(121, "Couldn't get mail server response codes");
2112 $_retVal = false;
2113 break;
2114 }
2115 $this->log .= $server_response;
2116 $limit++;
2117 }
2118
2119 $this->lastretval = substr($server_response, 0, 3);
2120
2121 if (!(substr($server_response, 0, 3) == $response)) {
2122 $this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: ".$server_response);
2123 $_retVal = false;
2124 }
2125
2126 return $_retVal;
2127 }
2128
2129 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2138 public function socket_send_str($_strSend, $_returnCode = null, $CRLF = "\r\n")
2139 {
2140 // phpcs:enable
2141 if ($this->_debug) {
2142 $this->log .= $_strSend; // @CHANGE LDR for log
2143 }
2144 fwrite($this->socket, $_strSend.$CRLF);
2145 if ($this->_debug) {
2146 $this->log .= ' ('.$_returnCode.')'.$CRLF;
2147 }
2148
2149 if ($_returnCode) {
2150 return $this->server_parse($this->socket, $_returnCode);
2151 }
2152
2153 return null;
2154 }
2155
2156 // =============================================================
2157 // ** Error handling methods
2158
2166 private function _setErr($_errNum, $_errMsg)
2167 {
2168 $this->_smtpsErrors[] = array(
2169 'num' => $_errNum,
2170 'msg' => $_errMsg,
2171 );
2172 }
2173
2179 public function getErrors()
2180 {
2181 $_errMsg = array();
2182
2183 if (is_array($this->_smtpsErrors)) {
2184 foreach ($this->_smtpsErrors as $_err => $_info) {
2185 $_errMsg[] = 'Error ['.$_info['num'].']: '.$_info['msg'];
2186 }
2187 }
2188
2189 return implode("\n", $_errMsg);
2190 }
2191}
2192
2193
2194// =============================================================
2195// ** CSV Version Control Info
2196
global $dolibarr_main_url_root
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to construct and send SMTP compliant email, even to a secure SMTP server, regardless of platfor...
_getBoundary($type='mixed')
Retrieves the MIME message Boundary.
setConfig($_strConfigPath=null)
setConfig() is used to populate select class properties from either a user defined INI file or the sy...
sendMsg()
Now send the message.
getErrors()
Returns applicative errors codes and messages for Class (not the SMTP error code)
setCharSet($_strCharSet)
Character set used for current message Character set is defaulted to 'iso-8859-1';.
setSubject($_strSubject='')
Message Subject.
getPriority()
Message Content Priority Message Priority values:
setAuthType($_strAuthType)
Authentication method to use (the one of the send context)
setReferences($_strReferences)
Set References in the list of Msg-Id.
getMD5flag()
Gets flag which determines whether to calculate message MD5 checksum.
socket_send_str($_strSend, $_returnCode=null, $CRLF="\r\n")
Send str.
_strip_email($_strAddr)
Returns an array of the various parts of an email address This assumes a well formed address:
getTransEncodeType()
Retrieves the Content-Transfer-Encoding.
setTrackId($_val='')
Set trackid.
setToken($_strToken)
User token for OAUTH2.
setInReplyTo($_strInReplyTo)
Set References in the list of Msg-Id.
buildRCPTlist()
build RECIPIENT List, all addresses who will receive this message
getBodyContent()
Retrieves the Message Content.
_buildAddrList($_type, $_addrList)
Inserts given addresses into structured format.
getInReplyTo()
Retrieves the InReplyTo from which mail we reply to.
setOptions($_options=array())
Set options.
_server_connect()
Attempt a connection to mail server.
setBodyContent($strContent, $strType='plain')
Message Content.
server_parse($socket, $response)
This function has been modified as provided by SirSir to allow multiline responses when using SMTP Ex...
setTransportType($_type=0)
Determines the method inwhich the messages are to be sent.
getBCC()
Retrieves the BCC Address[es] inwhich to send mail to.
setAttachment($strContent, $strFileName='unknown', $strMimeType='unknown', $strCid='')
File attachments are added to the content array as sub-arrays, allowing for multiple attachments for ...
_setBoundary()
Generates Random string for MIME message Boundary.
getTo()
Retrieves the TO Address[es] inwhich to send mail to.
setPort($_intPort)
Defines the Port Number of the Mail Server to use The default is 25 This is used only with 'socket' b...
getID()
Retrieves the User Name for authentication on Mail Server.
setBCC($_strBCC)
BCC Address[es] inwhich to send mail to.
setReplyTo($_strReplyTo)
Reply-To Address from which mail will be the reply-to.
getToken()
Retrieves the User token for OAUTH2.
setSensitivity($_value=0)
Message Content Sensitivity Message Sensitivity values:
setCC($_strCC)
CC Address[es] inwhich to send mail to.
getSMTPTimeout()
Get socket timeout.
setTO($_addrTo)
TO Address[es] inwhich to send mail to.
setTransEncodeType($_strTransEncodeType)
Content-Transfer-Encoding, Defaulted to '0' [ZERO] This can be changed for 2byte characters sets Know...
get_email_list($_which=null)
Returns an array of addresses for a specific type; TO, CC or BCC.
setMD5flag($_flag=false)
Set flag which determines whether to calculate message MD5 checksum.
getCharSet()
Retrieves the Character set used for current message.
getCC()
Retrieves the CC Address[es] inwhich to send mail to.
getDeliveryReceipt()
get delivery receipt
getTrackId()
get trackid
setFrom($_strFrom)
FROM Address from which mail will be sent.
get_RCPT_list()
Returns an array of bare addresses for use with 'RCPT TO:' This is a "build as you go" method.
_getTextTransferEncoding($text)
Content-Transfer-Encoding of a text part: the text is sent as is, so it is '8bit' when it has non ASC...
setID($_strID)
User Name for authentication on Mail Server.
getMoreInHeader()
get moreInHeader
getPW()
Retrieves the User Password for authentication on Mail Server.
getSubject()
Retrieves the Message Subject.
getXheader()
Retrieves the Message X-Header Content.
setErrorsTo($_strErrorsTo)
Set errors to.
setImageInline($strContent, $strImageName='unknown', $strMimeType='unknown', $strImageCid='unknown')
Image attachments are added to the content array as sub-arrays, allowing for multiple images for each...
setMessageID($_msgId='')
Set Message-ID.
setHost($_strHost)
Defines the Host Name or IP of the Mail Server to use.
getFrom($_part=true)
Retrieves the Address from which mail will be sent.
getHost()
Retrieves the Host Name or IP of the Mail Server to use This is used only with 'socket' based mail tr...
setPW($_strPW)
User Password for authentication on Mail Server.
getReplyTo($_part=true)
Retrieves the Address from which mail will be the reply-to.
setPriority($_value=3)
Message Content Priority Message Priority values:
setMoreInHeader($_val='')
Set moreInHeader.
getErrorsTo($_part=true)
Get errors to.
getSensitivity()
Returns Message Content Sensitivity string Message Sensitivity values:
setSMTPTimeout($timeout)
Set socket timeout.
getPort()
Retrieves the Port Number of the Mail Server to use This is used only with 'socket' based mail transm...
getTransportType()
Return the method inwhich the message is to be sent.
setMailPath($_path)
Path to the sendmail executable.
getTransEncode()
Retrieves the Content-Transfer-Encoding.
getReferences()
Retrieves the References from which mail will be the reply-to.
setTransEncode($_strTransEncode)
Content-Transfer-Encoding, Defaulted to '7bit' This can be changed for 2byte characters sets Known En...
_server_authenticate($withauth=true)
Attempt mail server authentication for a secure connection.
setDebug($_vDebug=false)
Set debug.
setDeliveryReceipt($_val=0)
Set delivery receipt.
_setErr($_errNum, $_errMsg)
Defines errors codes and messages for Class.
getHeader()
Constructs and returns message header.
setXheader($strXdata)
Message X-Header Content This is a simple "insert".
is_ip($ip)
This function evaluates a string that should be a valid IPv4 Note: For ip 169.254....
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
getDomainFromURL($url, $mode=0)
Function get second level domain name.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.