dolibarr 22.0.5
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-2025 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
551 private function _server_authenticate()
552 {
553 // phpcs:enable
554 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
555 // Send the RFC2554 specified EHLO.
556 // This improvement as provided by 'SirSir' to
557 // accommodate both SMTP AND ESMTP capable servers
558 $host = $this->getHost();
559 $usetls = preg_match('@tls://@i', $host);
560
561 $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
562 $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
563 $host = preg_replace('@tls://@i', '', $host); // Remove prefix
564
565 if ($usetls && getDolGlobalString('MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO')) {
566 $host = 'tls://'.$host;
567 }
568
569 $hosth = $host; // so for example 'localhost' or 'smtp-relay.gmail.com'
570
571 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
572 if (!is_numeric(getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO'))) {
573 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is a string, we use it as domain name
574 $hosth = getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO');
575 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 1) {
576 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 1, we use the domain in the from.
577 // So if the from to is 'aaa <bbb@ccc.com>', we will keep 'ccc.com'
578 $hosth = (string) $this->getFrom('addr');
579 $hosth = preg_replace('/^.*</', '', $hosth);
580 $hosth = preg_replace('/>.*$/', '', $hosth);
581 $hosth = preg_replace('/.*@/', '', $hosth);
582 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 2) {
583 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 2, we use the domain in the $dolibarr_main_url_root.
586 }
587 }
588
589 if ($_retVal = $this->socket_send_str('EHLO '.$hosth, '250')) {
590 if ($usetls) {
591 /*
592 The following dialog illustrates how a client and server can start a TLS STARTTLS session:
593 S: <waits for connection on TCP port 25>
594 C: <opens connection>
595 S: 220 mail.imc.org SMTP service ready
596 C: EHLO mail.ietf.org
597 S: 250-mail.imc.org offers a warm hug of welcome
598 S: 250 STARTTLS
599 C: STARTTLS
600 S: 220 Go ahead
601 C: <starts TLS negotiation>
602 C & S: <negotiate a TLS session>
603 C & S: <check result of negotiation>
604 // Second pass EHLO
605 C: EHLO client-domain.com
606 S: 250-server-domain.com
607 S: 250 AUTH LOGIN
608 C: <continues by sending an SMTP command
609
610 Another example here:
611 S: 220 smtp.server.com Simple Mail Transfer Service Ready
612 C: EHLO client.example.com
613 S: 250-smtp.server.com Hello client.example.com
614 S: 250-SIZE 1000000
615 S: 250-AUTH LOGIN PLAIN CRAM-MD5
616 S: 250-STARTTLS
617 S: 250 HELP
618 C: STARTTLS
619 S: 220 TLS go ahead
620 C: EHLO client.example.com *
621 S: 250-smtp.server.com Hello client.example.com
622 S: 250-SIZE 1000000
623 S: 250-AUTH LOGIN PLAIN CRAM-MD5
624 S: 250 HELP
625 C: AUTH LOGIN
626 S: 334 VXNlcm5hbWU6
627 C: adlxdkej
628 S: 334 UGFzc3dvcmQ6
629 C: lkujsefxlj
630 S: 235 2.7.0 Authentication successful
631 C: MAIL FROM:<mail@samlogic.com>
632 S: 250 OK
633 C: RCPT TO:<john@mail.com>
634 S: 250 OK
635 C: DATA
636 S: 354 Send message, end with a "." on a line by itself
637 C: <The message data (body text, subject, e-mail header, attachments etc) is sent>
638 S .
639 S: 250 OK, message accepted for delivery: queued as 12345
640 C: QUIT
641 S: 221 Bye
642 */
643 if (!$_retVal = $this->socket_send_str('STARTTLS', '220')) {
644 $this->_setErr(131, 'STARTTLS connection is not supported.');
645 return $_retVal;
646 }
647
648 // Before 5.6.7:
649 // STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_SSLv2_CLIENT|STREAM_CRYPTO_METHOD_SSLv3_CLIENT
650 // STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
651 // PHP >= 5.6.7:
652 // STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
653 // STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
654
655 $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
656 if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
657 $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
658 $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
659 }
660
661 if (!stream_socket_enable_crypto($this->socket, true, $crypto_method)) {
662 $this->_setErr(132, 'STARTTLS connection failed.');
663 return $_retVal;
664 }
665 // Most servers expect a 2nd pass of EHLO after TLS is established to get another time
666 // the answer with list of supported AUTH methods. They may differs between non STARTTLS and with STARTTLS.
667 if (! $_retVal = $this->socket_send_str('EHLO '.$hosth, '250')) {
668 $this->_setErr(126, '"'.$hosth.'" does not support authenticated connections or temporary error. Error after 2nd sending EHLO '.$hosth.' : '.$this->lastretval);
669 return $_retVal;
670 }
671 }
672
673 // Default authentication method is LOGIN
674 // Authentication method of the send context, else of the main setup
675 $authtype = $this->_smtpsAuthType ? $this->_smtpsAuthType : getDolGlobalString('MAIN_MAIL_SMTPS_AUTH_TYPE', 'LOGIN');
676
677 // Send Authentication to Server
678 // Check for errors along the way
679 switch ($authtype) {
680 case 'NONE':
681 // 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.
682 $_retVal = true;
683 break;
684 case 'PLAIN':
685 $_retVal = $this->socket_send_str('AUTH PLAIN', '334');
686 if (!$_retVal) {
687 // The login and password must not be sent if the server does not wait for them
688 $this->_setErr(130, 'Error when asking for AUTH PLAIN');
689 } else {
690 // The error here just means the ID/password combo doesn't work.
691 $_retVal = $this->socket_send_str(base64_encode("\0".$this->_smtpsID."\0".$this->_smtpsPW), '235');
692 }
693 break;
694 case 'XOAUTH2':
695 // "user=$email\1auth=Bearer $token\1\1"
696 $user = $this->_smtpsID;
697 $token = $this->_smtpsToken;
698 $initRes = "user=".$user."\001auth=Bearer ".$token."\001\001";
699 $_retVal = $this->socket_send_str('AUTH XOAUTH2 '.base64_encode($initRes), '235');
700 if (!$_retVal) {
701 $this->_setErr(130, 'Error when asking for AUTH XOAUTH2');
702 }
703 break;
704 case 'LOGIN': // most common case
705 default:
706 $_retVal = $this->socket_send_str('AUTH LOGIN', '334');
707 if (!$_retVal) {
708 $this->_setErr(130, 'Error when asking for AUTH LOGIN');
709 } else {
710 // User name will not return any error, server will take anything we give it.
711 $this->socket_send_str(base64_encode((string) $this->_smtpsID), '334');
712 // The error here just means the ID/password combo doesn't work.
713 // There is no method to determine which is the problem, ID or password
714 $_retVal = $this->socket_send_str(base64_encode((string) $this->_smtpsPW), '235');
715 }
716 break;
717 }
718 if (!$_retVal) {
719 $this->_setErr(130, 'Invalid Authentication Credentials.');
720 }
721 } else {
722 $this->_setErr(126, '"'.$host.'" refused the EHLO command. Error after sending EHLO '.$hosth.' : '.$this->lastretval);
723 }
724
725 return $_retVal;
726 }
727
733 public function sendMsg()
734 {
735 require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
736
737 // Default return value
738 $_retVal = false;
739
740 // Connect to Server
741 if ($this->socket = $this->_server_connect()) {
742 // If a User ID *and* a password is given, assume Authentication is desired
743 if (!empty($this->_smtpsID) && (!empty($this->_smtpsPW) || !empty($this->_smtpsToken))) {
744 // Send the RFC2554 specified EHLO.
745 $_retVal = $this->_server_authenticate();
746 } else {
747 // This is a "normal" SMTP Server "handshack"
748 // Send the RFC821 specified HELO.
749 $host = $this->getHost();
750 $usetls = preg_match('@tls://@i', $host);
751
752 $host = preg_replace('@tcp://@i', '', $host); // Remove prefix
753 $host = preg_replace('@ssl://@i', '', $host); // Remove prefix
754 $host = preg_replace('@tls://@i', '', $host); // Remove prefix
755
756 if ($usetls && getDolGlobalString('MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO')) {
757 $host = 'tls://'.$host;
758 }
759
760 $hosth = $host;
761
762 if (getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO')) {
763 if (!is_numeric(getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO'))) {
764 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is a string, we use it as domain name
765 $hosth = getDolGlobalString('MAIL_SMTP_USE_FROM_FOR_HELO');
766 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 1) {
767 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 1, we use the domain in the from.
768 // So if the from to is 'aaa <bbb@ccc.com>', we will keep 'ccc.com'
769 $hosth = (string) $this->getFrom('addr');
770 $hosth = preg_replace('/^.*</', '', $hosth);
771 $hosth = preg_replace('/>.*$/', '', $hosth);
772 $hosth = preg_replace('/.*@/', '', $hosth);
773 } elseif (getDolGlobalInt('MAIL_SMTP_USE_FROM_FOR_HELO') == 2) {
774 // If value of MAIL_SMTP_USE_FROM_FOR_HELO is 2, we use the domain in the $dolibarr_main_url_root.
777 }
778 }
779
780 // Send the HELO message to the SMTP server
781 $_retVal = $this->socket_send_str('HELO '.$hosth, '250');
782 }
783
784 // Well, did we get the server answer with correct code ?
785 if ($_retVal) {
786 // From this point onward most server response codes should be 250
787 // Specify who the mail is from....
788 // This has to be the raw email address, strip the "name" off
789 $resultmailfrom = $this->socket_send_str('MAIL FROM: '.$this->getFrom('addr'), '250');
790 if (!$resultmailfrom) {
791 fclose($this->socket);
792 return false;
793 }
794
795 // 'RCPT TO:' must be given a single address, so this has to loop
796 // through the list of addresses, regardless of TO, CC or BCC
797 // and send it out "single file"
798 foreach ($this->get_RCPT_list() as $_address) {
799 /* Note:
800 * BCC email addresses must be listed in the RCPT TO command list,
801 * but the BCC header should not be printed under the DATA command.
802 * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
803 */
804
805 /*
806 * TODO
807 * After each 'RCPT TO:' is sent, we need to make sure it was kosher,
808 * if not, the whole message will fail
809 * If any email address fails, we will need to RESET the connection,
810 * mark the last address as "bad" and start the address loop over again.
811 * If any address fails, the entire message fails.
812 */
813 if (!$this->socket_send_str('RCPT TO: <'.$_address.'>', '250')) {
814 // Stop here, sending DATA would desynchronize the SMTP responses
815 fclose($this->socket);
816 return false;
817 }
818 }
819
820 // Tell the server we are ready to start sending data
821 // with any custom headers...
822 // This is the last response code we look for until the end of the message.
823 if (!$this->socket_send_str('DATA', '354')) {
824 fclose($this->socket);
825 return false;
826 }
827
828 // Now we are ready for the message...
829 // Ok, all the ingredients are mixed in let's cook this puppy...
830 $_retVal = $this->socket_send_str($this->getHeader().$this->getBodyContent()."\r\n".'.', '250');
831
832 // Now tell the server we are done and close the socket...
833 $this->socket_send_str('QUIT');
834 } else {
835 // We got error code into $this->lastretval
836 }
837
838 fclose($this->socket);
839 }
840
841 return $_retVal;
842 }
843
844 // =============================================================
845 // ** Setter & Getter methods
846
847 // ** Basic System configuration
848
874 public function setConfig($_strConfigPath = null)
875 {
880 $_retVal = true;
881
882 // if we have a path...
883 if (!empty($_strConfigPath)) {
884 // If the path is not valid, this will NOT generate an error,
885 // it will simply return false.
886 if (!@include $_strConfigPath) {
887 $this->_setErr(110, '"'.$_strConfigPath.'" is not a valid path.');
888 $_retVal = false;
889 }
890 } else {
891 // Read the Systems php.ini file
892 // Set these properties ONLY if they are set in the php.ini file.
893 // Otherwise the default values will be used.
894 if ($_host = ini_get('SMTPs')) {
895 $this->setHost($_host);
896 }
897
898 if ($_port = ini_get('smtp_port')) {
899 $this->setPort($_port);
900 }
901
902 if ($_from = ini_get('sendmail_from')) {
903 $this->setFrom($_from);
904 }
905 }
906
907 // Send back what we have
908 return $_retVal;
909 }
910
920 public function setTransportType($_type = 0)
921 {
922 if ((is_numeric($_type)) && (($_type >= 0) && ($_type <= 3))) {
923 $this->_transportType = $_type;
924 }
925 }
926
935 public function getTransportType()
936 {
937 return $this->_transportType;
938 }
939
946 public function setMailPath($_path)
947 {
948 // This feature is not yet implemented
949 return true;
950
951 //if ( $_path ) $this->_mailPath = $_path;
952 }
953
962 public function setHost($_strHost)
963 {
964 if ($_strHost) {
965 $this->_smtpsHost = $_strHost;
966 }
967 }
968
975 public function getHost()
976 {
977 return $this->_smtpsHost;
978 }
979
988 public function setPort($_intPort)
989 {
990 if ((is_numeric($_intPort)) &&
991 (($_intPort >= 1) && ($_intPort <= 65536))) {
992 $this->_smtpsPort = (int) $_intPort;
993 }
994 }
995
1002 public function getPort()
1003 {
1004 return (int) $this->_smtpsPort;
1005 }
1006
1013 public function setID($_strID)
1014 {
1015 $this->_smtpsID = $_strID;
1016 }
1017
1023 public function getID()
1024 {
1025 return $this->_smtpsID;
1026 }
1027
1034 public function setPW($_strPW)
1035 {
1036 $this->_smtpsPW = $_strPW;
1037 }
1038
1044 public function getPW()
1045 {
1046 return $this->_smtpsPW;
1047 }
1048
1055 public function setToken($_strToken)
1056 {
1057 $this->_smtpsToken = $_strToken;
1058 }
1059
1066 public function setAuthType($_strAuthType)
1067 {
1068 $this->_smtpsAuthType = (string) $_strAuthType;
1069 }
1070
1076 public function getToken()
1077 {
1078 return $this->_smtpsToken;
1079 }
1080
1088 public function setCharSet($_strCharSet)
1089 {
1090 if ($_strCharSet) {
1091 $this->_smtpsCharSet = $_strCharSet;
1092 }
1093 }
1094
1100 public function getCharSet()
1101 {
1102 return $this->_smtpsCharSet;
1103 }
1104
1120 public function setTransEncode($_strTransEncode)
1121 {
1122 if (array_search($_strTransEncode, $this->_smtpsTransEncodeTypes)) {
1123 $this->_smtpsTransEncode = $_strTransEncode;
1124 }
1125 }
1126
1132 public function getTransEncode()
1133 {
1134 return $this->_smtpsTransEncode;
1135 }
1136
1152 public function setTransEncodeType($_strTransEncodeType)
1153 {
1154 if (array_search($_strTransEncodeType, $this->_smtpsTransEncodeTypes)) {
1155 $this->_smtpsTransEncodeType = $_strTransEncodeType;
1156 }
1157 }
1158
1164 public function getTransEncodeType()
1165 {
1166 return $this->_smtpsTransEncodeTypes[$this->_smtpsTransEncodeType];
1167 }
1168
1169
1170 // ** Message Construction
1171
1178 public function setFrom($_strFrom)
1179 {
1180 if ($_strFrom) {
1181 $this->_msgFrom = $this->_strip_email($_strFrom);
1182 }
1183 }
1184
1191 public function getFrom($_part = true)
1192 {
1193 $_retValue = '';
1194
1195 if ($_part === true || $this->_msgFrom === null) {
1196 $_retValue = $this->_msgFrom;
1197 } else {
1198 $_retValue = $this->_msgFrom[$_part];
1199 }
1200
1201 return $_retValue;
1202 }
1203
1210 public function setReplyTo($_strReplyTo)
1211 {
1212 if ($_strReplyTo) {
1213 $this->_msgReplyTo = $this->_strip_email($_strReplyTo);
1214 }
1215 }
1216
1223 public function getReplyTo($_part = true)
1224 {
1225 $_retValue = '';
1226
1227 if ($_part === true) {
1228 $_retValue = $this->_msgReplyTo;
1229 } else {
1230 $_retValue = $this->_msgReplyTo[$_part];
1231 }
1232
1233 return $_retValue;
1234 }
1235
1242 public function setInReplyTo($_strInReplyTo)
1243 {
1244 if ($_strInReplyTo) {
1245 $this->_msgInReplyTo = $_strInReplyTo;
1246 }
1247 }
1248
1254 public function getInReplyTo()
1255 {
1256 $_retValue = $this->_msgInReplyTo;
1257
1258 return $_retValue;
1259 }
1260
1267 public function setReferences($_strReferences)
1268 {
1269 if ($_strReferences) {
1270 $this->_msgReferences = $_strReferences;
1271 }
1272 }
1273
1279 public function getReferences()
1280 {
1281 $_retValue = $this->_msgReferences;
1282
1283 return $_retValue;
1284 }
1285
1295 private function _buildAddrList($_type, $_addrList)
1296 {
1297 // Pull existing list
1298 $aryHost = $this->_msgRecipients;
1299
1300 // Only run this if we have something
1301 if (!empty($_addrList)) {
1302 // $_addrList can be a STRING or an array
1303 if (is_string($_addrList)) {
1304 // This could be a COMMA delimited string
1305 if (strstr($_addrList, ',')) {
1306 // "explode "list" into an array
1307 $_addrList = explode(',', $_addrList);
1308 } else {
1309 // Stick it in an array
1310 $_addrList = array($_addrList);
1311 }
1312 }
1313
1314 // take the array of addresses and split them further
1315 foreach ($_addrList as $_strAddr) {
1316 // Strip off the end '>'
1317 $_strAddr = str_replace('>', '', $_strAddr);
1318
1319 // Separate "Real Name" from eMail address
1320 $_tmpaddr = null;
1321 $_tmpaddr = explode('<', $_strAddr);
1322
1323 // We have a "Real Name" and eMail address
1324 if (count($_tmpaddr) == 2) {
1325 $_tmpHost = explode('@', $_tmpaddr[1]);
1326 $_tmpaddr[0] = trim($_tmpaddr[0], ' ">');
1327 $aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = $_tmpaddr[0];
1328 } else {
1329 // We only have an eMail address
1330 // Strip off the beginning '<'
1331 $_strAddr = str_replace('<', '', $_strAddr);
1332
1333 $_tmpHost = explode('@', $_strAddr);
1334 $_tmpHost[0] = trim($_tmpHost[0]);
1335 $_tmpHost[1] = trim($_tmpHost[1]);
1336
1337 $aryHost[$_tmpHost[1]][$_type][$_tmpHost[0]] = '';
1338 }
1339 }
1340 }
1341 // replace list
1342 $this->_msgRecipients = $aryHost;
1343 }
1344
1345 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1362 private function _strip_email($_strAddr)
1363 {
1364 // phpcs:enable
1365 $_aryEmail = array();
1366 // Keep the original
1367 $_aryEmail['org'] = $_strAddr;
1368
1369 // Set entire string to Lower Case
1370 $_strAddr = strtolower($_strAddr);
1371
1372 // Drop "stuff' off the end
1373 $_strAddr = trim($_strAddr, ' ">');
1374
1375 // Separate "Real Name" from eMail address, if we have one
1376 $_tmpAry = explode('<', $_strAddr);
1377
1378 // Do we have a "Real name"
1379 if (count($_tmpAry) == 2) {
1380 // We may not really have a "Real Name"
1381 if ($_tmpAry[0]) {
1382 $_aryEmail['real'] = trim($_tmpAry[0], ' ">');
1383 }
1384
1385 $_aryEmail['addr'] = $_tmpAry[1];
1386 } else {
1387 $_aryEmail['addr'] = $_tmpAry[0];
1388 }
1389
1390 // Pull User Name and Host.tld apart
1391 $_tmpHost = explode('@', $_aryEmail['addr']);
1392 $_aryEmail['user'] = $_tmpHost[0];
1393 $_aryEmail['host'] = $_tmpHost[1];
1394
1395 // Put the brackets back around the address
1396 $_aryEmail['addr'] = '<'.$_aryEmail['addr'].'>';
1397
1398 return $_aryEmail;
1399 }
1400
1401 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1409 public function get_RCPT_list()
1410 {
1411 // phpcs:enable
1415 $_RCPT_list = array();
1416
1417 // walk down Recipients array and pull just email addresses
1418 foreach ($this->_msgRecipients as $_host => $_list) {
1419 foreach ($_list as $_subList) {
1420 foreach ($_subList as $_name => $_addr) {
1421 // build RCPT list
1422 $_RCPT_list[] = $_name.'@'.$_host;
1423 }
1424 }
1425 }
1426
1427 return $_RCPT_list;
1428 }
1429
1430 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1437 public function get_email_list($_which = null)
1438 {
1439 // phpcs:enable
1440 // We need to know which address segment to pull
1441 if ($_which) {
1442 // Make sure we have addresses to process
1443 if ($this->_msgRecipients) {
1444 $_RCPT_list = array();
1445 // walk down Recipients array and pull just email addresses
1446 foreach ($this->_msgRecipients as $_host => $_list) {
1447 if (!empty($this->_msgRecipients[$_host][$_which])) {
1448 foreach ($this->_msgRecipients[$_host][$_which] as $_addr => $_realName) {
1449 if ($_realName) { // @CHANGE LDR
1450 $_realName = '"'.$_realName.'"';
1451 $_RCPT_list[] = $_realName.' <'.$_addr.'@'.$_host.'>';
1452 } else {
1453 $_RCPT_list[] = $_addr.'@'.$_host;
1454 }
1455 }
1456 }
1457 }
1458
1459 return implode(', ', $_RCPT_list);
1460 } else {
1461 $this->_setErr(101, 'No eMail Address for message to be sent to.');
1462 return false;
1463 }
1464 } else {
1465 $this->_setErr(102, 'eMail type not defined.');
1466 return false;
1467 }
1468 }
1469
1476 public function setTO($_addrTo)
1477 {
1478 if ($_addrTo) {
1479 $this->_buildAddrList('to', $_addrTo);
1480 }
1481 }
1482
1488 public function getTo()
1489 {
1490 return $this->get_email_list('to');
1491 }
1492
1499 public function setCC($_strCC)
1500 {
1501 if ($_strCC) {
1502 $this->_buildAddrList('cc', $_strCC);
1503 }
1504 }
1505
1511 public function getCC()
1512 {
1513 return $this->get_email_list('cc');
1514 }
1515
1522 public function setBCC($_strBCC)
1523 {
1524 if ($_strBCC) {
1525 $this->_buildAddrList('bcc', $_strBCC);
1526 }
1527 }
1528
1534 public function getBCC()
1535 {
1536 return $this->get_email_list('bcc');
1537 }
1538
1545 public function setSubject($_strSubject = '')
1546 {
1547 if ($_strSubject) {
1548 $this->_msgSubject = $_strSubject;
1549 }
1550 }
1551
1557 public function getSubject()
1558 {
1559 return $this->_msgSubject;
1560 }
1561
1567 public function getHeader()
1568 {
1569 $_header = 'From: '.$this->getFrom('org')."\r\n"
1570 . 'To: '.$this->getTo()."\r\n";
1571
1572 if ($this->getCC()) {
1573 $_header .= 'Cc: '.$this->getCC()."\r\n";
1574 }
1575
1576 /* Note:
1577 * BCC email addresses must be listed in the RCPT TO command list,
1578 * but the BCC header should not be printed under the DATA command.
1579 * So it is included into the function sendMsg() but not here.
1580 * http://stackoverflow.com/questions/2750211/sending-bcc-emails-using-a-smtp-server
1581 */
1582 /*
1583 if ( $this->getBCC() )
1584 $_header .= 'Bcc: ' . $this->getBCC() . "\r\n";
1585 */
1586
1587 $host = dol_getprefix('email');
1588
1589 $_header .= 'Subject: '.$this->getSubject()."\r\n";
1590 $_header .= 'Date: '.date("r")."\r\n";
1591
1592 $trackid = $this->getTrackId();
1593 if ($trackid) {
1594 $_header .= 'Message-ID: <'.(empty($this->_msgId) ? uniqid().'.SMTPs-dolibarr-'.$trackid.'@'.$host : $this->_msgId).">\r\n";
1595 $_header .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host."\r\n";
1596 } else {
1597 $_header .= 'Message-ID: <'.(empty($this->_msgId) ? uniqid().'.SMTPs@'.$host : $this->_msgId).">\r\n";
1598 }
1599 if (!empty($_SERVER['REMOTE_ADDR'])) {
1600 $_header .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR']."\r\n";
1601 }
1602 if ($this->getMoreInHeader()) {
1603 // Value must include the "\r\n". With MAIN_FIX_FOR_BUGGED_MTA, CMailFile gives "\n", but SMTP needs "\r\n"
1604 $_header .= preg_replace('/(?<!\r)\n/', "\r\n", $this->getMoreInHeader());
1605 }
1606
1607 if ($this->getSensitivity()) {
1608 $_header .= 'Sensitivity: '.$this->getSensitivity()."\r\n";
1609 }
1610
1611 if ($this->_msgPriority != 3) {
1612 $_header .= $this->getPriority();
1613 }
1614
1615
1616 // @CHANGE LDR
1617 if ($this->getDeliveryReceipt()) {
1618 $_header .= 'Disposition-Notification-To: '.$this->getFrom('addr')."\r\n";
1619 }
1620 if ($this->getErrorsTo()) {
1621 $_header .= 'Errors-To: '.$this->getErrorsTo('addr')."\r\n";
1622 }
1623 if ($this->getReplyTo()) {
1624 $_header .= "Reply-To: ".$this->getReplyTo('addr')."\r\n";
1625 }
1626
1627 $_header .= 'X-Mailer: Dolibarr version '.DOL_VERSION.' (using SMTPs Mailer)'."\r\n";
1628 $_header .= 'X-Dolibarr-Option: '.(getDolGlobalString('MAIN_MAIL_USE_MULTI_PART') ? 'MAIN_MAIL_USE_MULTI_PART' : 'No MAIN_MAIL_USE_MULTI_PART')."\r\n";
1629 $_header .= 'Mime-Version: 1.0'."\r\n";
1630
1631 // Add also $this->references and In-Reply-To
1632 if ($this->getInReplyTo()) {
1633 $_header .= "In-Reply-To: ".$this->getInReplyTo()."\r\n";
1634 }
1635 $references = $this->getReferences();
1636 if ($references) {
1637 // List of message ids:
1638 // Example "References: <id1@domain2.com> <id2@domain.com>
1639 $_header .= "References: ".implode(' ', $references)."\r\n";
1640 }
1641
1642 return $_header;
1643 }
1644
1652 public function setBodyContent($strContent, $strType = 'plain')
1653 {
1654 //if ( $strContent )
1655 //{
1656 if ($strType == 'html') {
1657 $strMimeType = 'text/html';
1658 } else {
1659 $strMimeType = 'text/plain';
1660 }
1661
1662 // Make RFC821 Compliant, replace bare linefeeds
1663 $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $strContent);
1664
1665 $strContentAltText = '';
1666 if ($strType == 'html') {
1667 // Similar code to forge a text from html is also in CMailFile.class.php
1668 $strContentAltText = preg_replace('/<head><title>.*<\/style><\/head>/', '', $strContent);
1669 $strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContentAltText);
1670 $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1671 $strContentAltText = trim(wordwrap($strContentAltText, 75, "\r\n"));
1672 }
1673
1674 // Make RFC2045 Compliant
1675 //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content
1676 $strContent = rtrim(wordwrap($strContent, 75, "\r\n")); // TODO Using this method creates unexpected line break on text/plain content.
1677
1678 $this->_msgContent[$strType] = array();
1679
1680 $this->_msgContent[$strType]['mimeType'] = $strMimeType;
1681 $this->_msgContent[$strType]['data'] = $strContent;
1682 $this->_msgContent[$strType]['dataText'] = $strContentAltText;
1683
1684 if ($this->getMD5flag()) {
1685 $this->_msgContent[$strType]['md5'] = dol_hash($strContent, '3');
1686 }
1687 //}
1688 }
1689
1695 public function getBodyContent()
1696 {
1697 global $conf;
1698
1699 // Generate a new Boundary string
1700 $this->_setBoundary();
1701
1702 // What type[s] of content do we have
1703 $_types = array_keys($this->_msgContent);
1704
1705 // How many content types do we have
1706 $keyCount = count($_types);
1707
1708 // If we have ZERO, we have a problem
1709 if ($keyCount === 0) {
1710 die("Sorry, no content");
1711 } elseif ($keyCount === 1 && !getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1712 // If we have ONE, we can use the simple format
1713 $_msgData = $this->_msgContent;
1714 $_msgData = $_msgData[$_types[0]];
1715
1716 $content = 'Content-Type: '.$_msgData['mimeType'].'; charset="'.$this->getCharSet().'"'."\r\n"
1717 . 'Content-Transfer-Encoding: '.$this->getTransEncodeType()."\r\n"
1718 . 'Content-Disposition: inline'."\r\n"
1719 . 'Content-Description: Message'."\r\n";
1720
1721 if ($this->getMD5flag()) {
1722 $content .= 'Content-MD5: '.$_msgData['md5']."\r\n";
1723 }
1724
1725 $content .= "\r\n"
1726 . $_msgData['data']."\r\n";
1727 } elseif ($keyCount >= 1 || getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1728 // If we have more than ONE, we use the multi-part format
1729 // Since this is an actual multi-part message
1730 // We need to define a content message Boundary
1731 // NOTE: This was 'multipart/alternative', but Windows based mail servers have issues with this.
1732
1733 //$content = 'Content-Type: multipart/related; boundary="' . $this->_getBoundary() . '"' . "\r\n";
1734 $content = 'Content-Type: multipart/mixed; boundary="'.$this->_getBoundary('mixed').'"'."\r\n";
1735
1736 // . "\r\n"
1737 // . 'This is a multi-part message in MIME format.' . "\r\n";
1738 $content .= "Content-Transfer-Encoding: 8bit\r\n";
1739 $content .= "\r\n";
1740
1741 $content .= "--".$this->_getBoundary('mixed')."\r\n";
1742
1743 if (array_key_exists('image', $this->_msgContent)) { // If inline image found
1744 $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
1745 $content .= "\r\n";
1746 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1747 }
1748
1749
1750 // $this->_msgContent must be sorted with key 'text' or 'html' first then 'image' then 'attachment'
1751
1752
1753 // Loop through message content array
1754 foreach ($this->_msgContent as $type => $_content) {
1755 if ($type == 'attachment') {
1756 // loop through all attachments
1757 foreach ($_content as $_file => $_data) {
1758 $content .= "--".$this->_getBoundary('mixed')."\r\n"
1759 . 'Content-Disposition: attachment; filename="'.$_data['fileName'].'"'."\r\n"
1760 . 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['fileName'].'"'."\r\n"
1761 . 'Content-Transfer-Encoding: base64'."\r\n"
1762 . 'Content-Description: '.$_data['fileName']."\r\n";
1763 if (!empty($_data['cid'])) {
1764 $content .= "X-Attachment-Id: ".$_data['cid']."\r\n";
1765 $content .= "Content-ID: <".$_data['cid'].">\r\n";
1766 }
1767 if ($this->getMD5flag()) {
1768 $content .= 'Content-MD5: '.$_data['md5']."\r\n";
1769 }
1770
1771 $content .= "\r\n".$_data['data']."\r\n\r\n";
1772 }
1773 } elseif ($type == 'image') {
1774 // @CHANGE LDR
1775 // loop through all images
1776 foreach ($_content as $_image => $_data) {
1777 $content .= "--".$this->_getBoundary('related')."\r\n"; // always related for an inline image
1778
1779 $content .= 'Content-Type: '.$_data['mimeType'].'; name="'.$_data['imageName'].'"'."\r\n"
1780 . 'Content-Transfer-Encoding: base64'."\r\n"
1781 . 'Content-Disposition: inline; filename="'.$_data['imageName'].'"'."\r\n"
1782 . 'Content-ID: <'.$_data['cid'].'> '."\r\n";
1783
1784 if ($this->getMD5flag()) {
1785 $content .= 'Content-MD5: '.$_data['md5']."\r\n";
1786 }
1787
1788 $content .= "\r\n"
1789 . $_data['data']."\r\n";
1790 }
1791
1792 // always end related and end alternative after inline images
1793 $content .= "--".$this->_getBoundary('related')."--\r\n";
1794 $content .= "\r\n--".$this->_getBoundary('alternative')."--\r\n";
1795 $content .= "\r\n";
1796 } else {
1797 if (array_key_exists('image', $this->_msgContent)) {
1798 $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
1799 $content .= "\r\n".($_content['dataText'] ? $_content['dataText'] : strip_tags($_content['data']))."\r\n"; // Add plain text message
1800 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1801 $content .= 'Content-Type: multipart/related; boundary="'.$this->_getBoundary('related').'"'."\r\n";
1802 $content .= "\r\n";
1803 $content .= "--".$this->_getBoundary('related')."\r\n";
1804 }
1805
1806 if (!array_key_exists('image', $this->_msgContent) && $_content['dataText'] && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1807 // Add plain text message part before html part
1808 $content .= 'Content-Type: multipart/alternative; boundary="'.$this->_getBoundary('alternative').'"'."\r\n";
1809 $content .= "\r\n";
1810 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1811
1812 $content .= "Content-Type: text/plain; charset=".$this->getCharSet()."\r\n";
1813 $content .= "\r\n".$_content['dataText']."\r\n";
1814 $content .= "--".$this->_getBoundary('alternative')."\r\n";
1815 }
1816
1817 $content .= 'Content-Type: '.$_content['mimeType'].'; charset='.$this->getCharSet();
1818
1819 $content .= "\r\n";
1820
1821 if ($this->getMD5flag()) {
1822 $content .= 'Content-MD5: '.$_content['md5']."\r\n";
1823 }
1824
1825 $content .= "\r\n".$_content['data']."\r\n";
1826
1827 if (!array_key_exists('image', $this->_msgContent) && $_content['dataText'] && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) {
1828 // Add plain text message part after html part
1829 $content .= "--".$this->_getBoundary('alternative')."--\r\n";
1830 }
1831
1832 $content .= "\r\n";
1833 }
1834 }
1835
1836 $content .= "--".$this->_getBoundary('mixed').'--'."\r\n";
1837 } else {
1838 die("Sorry, no content");
1839 }
1840
1841 return $content;
1842 }
1843
1854 public function setAttachment($strContent, $strFileName = 'unknown', $strMimeType = 'unknown', $strCid = '')
1855 {
1856 if ($strContent) {
1857 $strContent = rtrim(chunk_split(base64_encode($strContent), 76, "\r\n")); // 76 max is defined into http://tools.ietf.org/html/rfc2047
1858
1859 // The key is the file name and the hash of its content: the same file given twice is attached once, but 2 different
1860 // files with the same name (from different directories) are both attached.
1861 $attachmentkey = $strFileName.'-'.dol_hash($strContent, 'sha256');
1862
1863 $this->_msgContent['attachment'][$attachmentkey]['mimeType'] = $strMimeType;
1864 $this->_msgContent['attachment'][$attachmentkey]['fileName'] = $strFileName;
1865 $this->_msgContent['attachment'][$attachmentkey]['data'] = $strContent;
1866 $this->_msgContent['attachment'][$attachmentkey]['cid'] = $strCid; // If defined, it means this attachment must be shown inline
1867
1868 if ($this->getMD5flag()) {
1869 $this->_msgContent['attachment'][$attachmentkey]['md5'] = dol_hash($strContent, '3');
1870 }
1871 }
1872 }
1873
1874
1875 // @CHANGE LDR
1876
1887 public function setImageInline($strContent, $strImageName = 'unknown', $strMimeType = 'unknown', $strImageCid = 'unknown')
1888 {
1889 if ($strContent) {
1890 $this->_msgContent['image'][$strImageName]['mimeType'] = $strMimeType;
1891 $this->_msgContent['image'][$strImageName]['imageName'] = $strImageName;
1892 $this->_msgContent['image'][$strImageName]['cid'] = $strImageCid;
1893 $this->_msgContent['image'][$strImageName]['data'] = $strContent;
1894
1895 if ($this->getMD5flag()) {
1896 $this->_msgContent['image'][$strImageName]['md5'] = dol_hash($strContent, '3');
1897 }
1898 }
1899 }
1900 // END @CHANGE LDR
1901
1902
1914 public function setSensitivity($_value = 0)
1915 {
1916 if ((is_numeric($_value)) &&
1917 (($_value >= 0) && ($_value <= 3))) {
1918 $this->_msgSensitivity = $_value;
1919 }
1920 }
1921
1932 public function getSensitivity()
1933 {
1934 return $this->_arySensitivity[$this->_msgSensitivity];
1935 }
1936
1950 public function setPriority($_value = 3)
1951 {
1952 if ((is_numeric($_value)) &&
1953 (($_value >= 0) && ($_value <= 5))) {
1954 $this->_msgPriority = $_value;
1955 }
1956 }
1957
1970 public function getPriority()
1971 {
1972 return 'Importance: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
1973 . 'Priority: '.$this->_aryPriority[$this->_msgPriority]."\r\n"
1974 . 'X-Priority: '.$this->_msgPriority.' ('.$this->_aryPriority[$this->_msgPriority].')'."\r\n";
1975 }
1976
1983 public function setMD5flag($_flag = false)
1984 {
1985 $this->_smtpMD5 = $_flag;
1986 }
1987
1993 public function getMD5flag()
1994 {
1995 return $this->_smtpMD5;
1996 }
1997
2006 public function setXheader($strXdata)
2007 {
2008 if ($strXdata) {
2009 $this->_msgXheader[] = $strXdata;
2010 }
2011 }
2012
2018 public function getXheader()
2019 {
2020 return $this->_msgXheader;
2021 }
2022
2028 private function _setBoundary()
2029 {
2030 $this->_smtpsBoundary = "multipart_x.".time().".x_boundary";
2031 $this->_smtpsRelatedBoundary = 'mul_'.dol_hash(uniqid("dolibarr2"), '3');
2032 $this->_smtpsAlternativeBoundary = 'mul_'.dol_hash(uniqid("dolibarr3"), '3');
2033 }
2034
2041 private function _getBoundary($type = 'mixed')
2042 {
2043 if ($type == 'mixed') {
2044 return $this->_smtpsBoundary;
2045 } elseif ($type == 'related') {
2046 return $this->_smtpsRelatedBoundary;
2047 } elseif ($type == 'alternative') {
2048 return $this->_smtpsAlternativeBoundary;
2049 }
2050 return '';
2051 }
2052
2053 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2064 public function server_parse($socket, $response)
2065 {
2066 // phpcs:enable
2071 $_retVal = true;
2072
2073 $server_response = '';
2074
2075 // avoid infinite loop
2076 $limit = 0;
2077
2078 while (substr($server_response, 3, 1) != ' ' && $limit < 100) {
2079 // Read the whole line (a reply line longer than the read size would be read as 2 replies)
2080 if (!($server_response = fgets($socket))) {
2081 $this->_setErr(121, "Couldn't get mail server response codes");
2082 $_retVal = false;
2083 break;
2084 }
2085 $this->log .= $server_response;
2086 $limit++;
2087 }
2088
2089 $this->lastretval = substr($server_response, 0, 3);
2090
2091 if (!(substr($server_response, 0, 3) == $response)) {
2092 $this->_setErr(120, "Ran into problems sending Mail.\r\nResponse: ".$server_response);
2093 $_retVal = false;
2094 }
2095
2096 return $_retVal;
2097 }
2098
2099 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2108 public function socket_send_str($_strSend, $_returnCode = null, $CRLF = "\r\n")
2109 {
2110 // phpcs:enable
2111 if ($this->_debug) {
2112 $this->log .= $_strSend; // @CHANGE LDR for log
2113 }
2114 fwrite($this->socket, $_strSend.$CRLF);
2115 if ($this->_debug) {
2116 $this->log .= ' ('.$_returnCode.')'.$CRLF;
2117 }
2118
2119 if ($_returnCode) {
2120 return $this->server_parse($this->socket, $_returnCode);
2121 }
2122
2123 return null;
2124 }
2125
2126 // =============================================================
2127 // ** Error handling methods
2128
2136 private function _setErr($_errNum, $_errMsg)
2137 {
2138 $this->_smtpsErrors[] = array(
2139 'num' => $_errNum,
2140 'msg' => $_errMsg,
2141 );
2142 }
2143
2149 public function getErrors()
2150 {
2151 $_errMsg = array();
2152
2153 if (is_array($this->_smtpsErrors)) {
2154 foreach ($this->_smtpsErrors as $_err => $_info) {
2155 $_errMsg[] = 'Error ['.$_info['num'].']: '.$_info['msg'];
2156 }
2157 }
2158
2159 return implode("\n", $_errMsg);
2160 }
2161}
2162
2163
2164// =============================================================
2165// ** CSV Version Control Info
2166
global $dolibarr_main_url_root
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.
_server_authenticate()
Attempt mail server authentication for a secure connection.
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...
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.