<?php


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//////////////////////////////////////////////////////  SERVIDOR GMAIL ////////////////////////////////////////////////////////////////////

// para utilizar correo GMAIL Debe realizar los siguientes pasos

// 1- habilitar en xampp/php/php/php.ini  la siguiente  extension=php_openssl.dll  
// 2- ir gmail  
// mi cuenta
// Acceso y seguridad 
// al final habiitamos la opcion   Permitir el acceso de aplicaciones menos seguras: SÍ


// servidor por defecto = smtp.gmail.com 
// puerto por defecto = 465
// tipo seguridas = ssl 

////////////////////////////////////////////////////////  SERVIDOR HOTMAIL   //////////////////////////////////////////////////////

// habilitar en opciones, correo, POP E IMAP   permitir que los dispositivos y las aplicaciones utilicen POP

// servidor por defecto = smtp-mail.outlook.com	
// puerto por defecto = 587
// tipo seguridas = tls


////////////////////////////////////////////////////////  SERVIDOR LOCAL   //////////////////////////////////////////////////////

// servidor por defecto = server.servycompu.com 
// puerto por defecto = 587
// tipo seguridas = ninguna


	  if (!isset($_GET["codnota"])) { $codnota=$_POST["codnota"]; } else  { $codnota=$_GET["codnota"]; }	  // AGREGA correo reenvio 

include ("../conexion.php");


		
		       $parametros = "SELECT * FROM web_0000 ";
       $result_parametros = $mysqli->query($parametros);
       $row_para = $result_parametros->fetch_array();
    
	   $nomcom =  $row_para["NOMCOM"];

	   $clacor =  $row_para["CLACOR"];

	   $sercor =  $row_para["SERCOR"];
	   
echo   "Correo enviado desde: ";
echo   "<BR>";
echo   $coremp =  $row_para["COREMP"];

echo   "<BR>";
       $servidor_correo = substr($coremp, -9); 
	   $segcor =  $row_para["SEGCOR"];
	
	  $puecor =  $row_para["PUECOR"];
	

		       $factura= "SELECT cdgcli,dsccli, numcomp, cdgclave FROM facturas_notas WHERE codnota='$codnota' ";
       $result_factura = $mysqli->query($factura);
       $row_factura = $result_factura->fetch_array();
     
	   $cdgcli    =  $row_factura["cdgcli"];
	   $dsccli    =  $row_factura["dsccli"];
	   $numcomp   =  $row_factura["numcomp"];
	   $cdgclave  =  $row_factura["cdgclave"];
		

  	   $consulta = "SELECT  corcli, corcli2,CEDCLI FROM web_0301 WHERE cdgcli='$cdgcli'";
       $resultado = $mysqli->query($consulta);
       $row = $resultado->fetch_array();
       $corcli = $row["corcli"];
	   $corcli2 = $row["corcli2"];
	   $CEDCLI = $row["CEDCLI"];

     	  if (!isset($_POST["corcli"]))  { $corcli=$corcli;  } else  {  echo $corcli=$_POST["corcli"];   }	  // AGREGA correo reenvio 
		  if (!isset($_POST["corcli2"])) { $corcli2=$corcli2; } else  {   $corcli2=$_POST["corcli2"];}	  // AGREGA correo reenvio 
			$corcli3="correosice3@gmail.com";
  
  	 if ($servidor_correo == "gmail.com" )   {    // SI EL SERVIDOR DE CORREO ES GMAIL
  
echo   "Correo enviado por API GMAIL ";
echo   "<BR>";                 


require_once  '../Comprobantes_mensajes/vendor/autoload.php';
	
	function getClient(){
		$client = new Google_Client();
		$client->setApplicationName('GmailBox');
		$client->setScopes([Google_Service_Gmail::MAIL_GOOGLE_COM]);
		$client->setAuthConfig( '../Comprobantes_mensajes/client_secret.json');
		$client->setAccessType('offline');
		
		$credentialsPath = expandHomeDirectory( '../Comprobantes_mensajes/token.json');
		if(isset($_GET['code'])){
			$authCode = trim($_GET['code']);		
			$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
			if (!file_exists(dirname($credentialsPath))) {
				mkdir(dirname($credentialsPath), 0700, true);
			}
			file_put_contents($credentialsPath, json_encode($accessToken));
			printf("Credentials saved to %s\n", $credentialsPath);
		}
		
		if (file_exists($credentialsPath)) {
			$accessToken = json_decode(file_get_contents($credentialsPath), true);
		} else {
			//$client->setRedirectUri('http://softcomcr.com/wccr');
			$authUrl = $client->createAuthUrl();
			echo '<a href="'.$authUrl.'">Dar acceso</a><br>';
			die;
		}
		
		$client->setAccessToken($accessToken);
		if ($client->isAccessTokenExpired()) {
			$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
			file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
		}
		return $client;
	}
	function expandHomeDirectory($path)
{
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
    }
    return str_replace('~', realpath($homeDirectory), $path);
}
	
	$client = getClient();
	

    
	$credentialsPath = expandHomeDirectory('../Comprobantes_mensajes/token.json');
	if (file_exists($credentialsPath)) {
		$arr_token = json_decode(file_get_contents($credentialsPath), true);
	}
	 
	$email = $coremp;	
	
	$client->setAccessToken($arr_token['access_token']);            
    $objGMail = new Google_Service_Gmail($client);

    $strMailContent = 'Saludos ' .$dsccli .' Adjunto encontrara su Nota de Credito Electronica';
  
    $strRawMessage = "";
    $boundary = uniqid(rand(), true);
    $subjectCharset = $charset = 'utf-8';
    $strToMailName =  $dsccli;
    $strToMail = $corcli;
    $strSesFromName = $nomcom;
    $strSesFromEmail = $coremp;
    $strSubject = 'Nota de Credito Electronica '. $nomcom  ;

    $strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n";
    $strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n";

    $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
    $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
 
 
                   /////////////      envia comprobante xml /////////////////////////////////////
			   
				   
    $filePath = '../FE/notaCredito/crt/mensajes/mns-'.$cdgclave.'.xml';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $cdgclave.'.xml';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= $strMailContent . "\r\n";
	
	
	                         ///////////////  envia mensajes de aceptacion ///////////////////////////
	
	    $filePath = '../FE/notaCredito/crt/comprobantes/'.$numcomp.'.xml';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $numcomp.'.xml';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
   // $strRawMessage .= $strMailContent . "\r\n";
	
	
	
	                                  ///////////////////////////   envia documento pdf ////////////////////////////
	
		    $filePath = '../FE/notaCredito/crt/NC_pdf/NC'.$numcomp.'.pdf';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $numcomp.'.pdf';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
   // $strRawMessage .= $strMailContent . "\r\n";
	

    //Send Mails
    //Prepare the message in message/rfc822
    try {
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
        $objSentMsg = $objGMail->users_messages->send("me", $msg);

      	$sel_envio="UPDATE facturas_notas SET estenvio=1 WHERE cdgclave = '$cdgclave'  "; //// se suma el consecutivo a contado numfaccre
	    	$mysqli->query($sel_envio);
			
  	 
	  echo "<BR>";
        print(' Correo 1 enviado a '.$corcli.' de Forma Exitosa ');
		
		echo $corcli_colono1 = substr($corcli, -15); 

    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['access_token']);
    }

	 
	 
	 
	if ( $corcli2 <> "") { 
     
	 
	 
	$client = getClient();
	

    
	$credentialsPath = expandHomeDirectory('../Comprobantes_mensajes/token.json');
	if (file_exists($credentialsPath)) {
		$arr_token = json_decode(file_get_contents($credentialsPath), true);
	}
	 
	$email = $coremp;	
	
	$client->setAccessToken($arr_token['access_token']);            
    $objGMail = new Google_Service_Gmail($client);

    $strMailContent = 'Saludos ' .$dsccli .' Adjunto encontrara su Nota de Credito Electronica';
  
    $strRawMessage = "";
    $boundary = uniqid(rand(), true);
    $subjectCharset = $charset = 'utf-8';
    $strToMailName =  $dsccli;
    $strToMail = $corcli2;
    $strSesFromName = $nomcom;
    $strSesFromEmail = $coremp;
    $strSubject = 'Nota de Credito Electronica '. $nomcom  ;

    $strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n";
    $strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n";

    $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
    $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
 
 
                   /////////////      envia comprobante xml /////////////////////////////////////
				   
  $filePath = '../FE/notaCredito/crt/mensajes/mns-'.$cdgclave.'.xml';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $cdgclave.'.xml';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= $strMailContent . "\r\n";
	
	
	                         ///////////////  envia mensajes de aceptacion ///////////////////////////
	
	    $filePath = '../FE/notaCredito/crt/comprobantes/'.$numcomp.'.xml';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $numcomp.'.xml';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
   // $strRawMessage .= $strMailContent . "\r\n";
	
	
	
	                                  ///////////////////////////   envia documento pdf ////////////////////////////
	
		    $filePath = '../FE/notaCredito/crt/NC_pdf/NC'.$numcomp.'.pdf';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $numcomp.'.pdf';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
   // $strRawMessage .= $strMailContent . "\r\n";
	

    //Send Mails
    //Prepare the message in message/rfc822
    try {
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
        $objSentMsg = $objGMail->users_messages->send("me", $msg);
	 
	  echo "<BR>";
        print(' Correo 2 enviado a '.$corcli2.' de Forma Exitosa ');
		
			echo "<BR>";
       // print($objSentMsg);

    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['access_token']);
    }
	
	
	
	    }
		
					$corcli_1 = substr($corcli, -6); 
				$corcli_2 = substr($corcli2, -6); 
				
				 $corcli_colono1 = substr($corcli, -15); 
				$corcli_colono2 = substr($corcli2, -15); 
				
				$corcli_palmatica1 = substr($corcli, -13); 
				$corcli_palmatica2 = substr($corcli2, -13); 
				//palmatica.com
				
				  echo "<BR>";
			//	grupocolono.com

 if ( ($corcli_1== ".go.cr" ) OR ($corcli_2== ".go.cr") OR ($corcli_colono1== "grupocolono.com")  OR ($corcli_colono2== "grupocolono.com") OR ($corcli_palmatica1== "palmatica.com") OR ($corcli_palmatica2== "palmatica.com") )   { 
	//if ($CEDCLI=="4000042139"){ // hace el envío al correo especial del ice 
	
	$client = getClient();
	

    
	$credentialsPath = expandHomeDirectory('../Comprobantes_mensajes/token.json');
	if (file_exists($credentialsPath)) {
		$arr_token = json_decode(file_get_contents($credentialsPath), true);
	}
	 
	$email = $coremp;	
	
	$client->setAccessToken($arr_token['access_token']);            
    $objGMail = new Google_Service_Gmail($client);

    $strMailContent = 'Saludos ' .$dsccli .' Adjunto encontrara su Nota de Credito Electronica';
	
  	 $strMailContent .= ' CORREO # 1: ' .$corcli .'  CORREO # 2: '.$corcli2;
	 
	// $strRawMessage .= $strMailContent . "\r\n";
	 
    $strRawMessage = "";
    $boundary = uniqid(rand(), true);
    $subjectCharset = $charset = 'utf-8';
    $strToMailName =  $dsccli;
    $strToMail = $corcli3;
    $strSesFromName = $nomcom;
    $strSesFromEmail = $coremp;
    $strSubject = 'Nota de Credito Electronica '. $nomcom  ;

    $strRawMessage .= 'To: ' .$strToMailName . " <" . $strToMail . ">" . "\r\n";
    $strRawMessage .= 'From: '.$strSesFromName . " <" . $strSesFromEmail . ">" . "\r\n";

    $strRawMessage .= 'Subject: =?' . $subjectCharset . '?B?' . base64_encode($strSubject) . "?=\r\n";
    $strRawMessage .= 'MIME-Version: 1.0' . "\r\n";
    $strRawMessage .= 'Content-type: Multipart/Mixed; boundary="' . $boundary . '"' . "\r\n";
 
 
                   /////////////      envia comprobante xml /////////////////////////////////////
			   
  $filePath = '../FE/notaCredito/crt/mensajes/mns-'.$cdgclave.'.xml';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $cdgclave.'.xml';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
    $strRawMessage .= $strMailContent . "\r\n";
	
	
	                         ///////////////  envia mensajes de aceptacion ///////////////////////////
	
	    $filePath = '../FE/notaCredito/crt/comprobantes/'.$numcomp.'.xml';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $numcomp.'.xml';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
   // $strRawMessage .= $strMailContent . "\r\n";
	

	
	                                  ///////////////////////////   envia documento pdf ////////////////////////////
	
		    $filePath = '../FE/notaCredito/crt/NC_pdf/NC'.$numcomp.'.pdf';
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mimeType = finfo_file($finfo, $filePath);
    $fileName = $numcomp.'.pdf';
    $fileData = base64_encode(file_get_contents($filePath));
	
	    $strRawMessage .= "\r\n--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: '. $mimeType .'; name="'. $fileName .'";' . "\r\n";            
    $strRawMessage .= 'Content-ID: <' . $strSesFromEmail . '>' . "\r\n";            
    $strRawMessage .= 'Content-Description: ' . $fileName . ';' . "\r\n";
    $strRawMessage .= 'Content-Disposition: attachment; filename="' . $fileName . '"; size=' . filesize($filePath). ';' . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
    $strRawMessage .= chunk_split(base64_encode(file_get_contents($filePath)), 76, "\n") . "\r\n";
    $strRawMessage .= "--{$boundary}\r\n";
    $strRawMessage .= 'Content-Type: text/html; charset=' . $charset . "\r\n";
    $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
   // $strRawMessage .= $strMailContent . "\r\n";
	

    //Send Mails
    //Prepare the message in message/rfc822
    try {
        // The message needs to be encoded in Base64URL
        $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
        $msg = new Google_Service_Gmail_Message();
        $msg->setRaw($mime);
        $objSentMsg = $objGMail->users_messages->send("me", $msg);
	 
	  echo "<BR>";
        print(' Correo 3 enviado a '.$corcli3.' de Forma Exitosa ');
		
			echo "<BR>";
       // print($objSentMsg);

    } catch (Exception $e) {
        print($e->getMessage());
        unset($_SESSION['access_token']);
    }	
	
		
	 }	
	 
	 
		} else  {     //  SI EL SERVIDOR DE CORREO NO ES GMAIL 

   /////////////////////////////////////////////////  INICIO DEL CORREO //////////////////////////////////////////

echo   "Correo enviado por PHPMAILER ";
echo   "<BR>";     


$rdir = str_replace("\\", "/", __DIR__);                    //Root Dir
require $rdir.'/PHPMailer/src/Exception.php';
require $rdir.'/PHPMailer/src/PHPMailer.php';
require $rdir.'/PHPMailer/src/SMTP.php';

//require 'vendor/autoload.php';


$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = $sercor;                  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = $coremp;             // SMTP username
    $mail->Password = $clacor;                          // SMTP password
    $mail->SMTPSecure = $segcor;                            // Enable SSL encryption, TLS also accepted with port 465
    $mail->Port = $puecor;                                    // TCP port to connect to
	
	

	

    //Recipients
    $mail->setFrom($coremp, $nomcom);          //This is the email your form sends From
    $mail->addAddress($corcli, $dsccli); // Add a recipient address
    //$mail->addAddress('contact@example.com');               // Name is optional
    //$mail->addReplyTo('info@example.com', 'Information');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    //Attachments	  
    $mail->AddAttachment('../FE/notaCredito/crt/comprobantes/'.$numcomp.'.xml');  
	$mail->AddAttachment('../FE/notaCredito/crt/NC_pdf/NC'.$numcomp.'.pdf');  
	$mail->AddAttachment('../FE/notaCredito/crt/mensajes/mns-'.$cdgclave.'.xml');  
	
	
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTM  
    $mail->Subject = 'Nota Credito Electronica '.$nomcom;
	$mail->AltBody = 'Nota Credito Electronica'; // optional - MsgHTML will create an alternate automatically  
	$mail->MsgHTML('Saludos ' .$dsccli .' Adjunto encontrara su Nota de Credito Electronica ');
	// $mail->MsgHTML(file_get_contents('contents.html'));
	
	// $mail->MsgHTML(file_get_contents('contents.html'));

    $mail->send();
	
	$sel_envio="UPDATE facturas_notas SET estenvio=1 WHERE cdgclave = '$cdgclave'  "; //// se suma el consecutivo a contado numfaccre
	    	$mysqli->query($sel_envio);
			
	  echo "<BR>";
        print(' Correo 1 enviado a '.$corcli.' de Forma Exitosa ');
		  echo "<BR>";
} catch (Exception $e) {
    echo 'Error en el envio.';
    echo 'Detalle: ' . $mail->ErrorInfo;
}
	
	
	
	if ( $corcli2 <> "") {
	
	  /////////////////////////////////////////////////  INICIO DEL SEGUNDO  CORREO //////////////////////////////////////////

 // Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function


$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
   $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = $sercor;                  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = $coremp;             // SMTP username
    $mail->Password = $clacor;                          // SMTP password
    $mail->SMTPSecure = $segcor;                            // Enable SSL encryption, TLS also accepted with port 465
    $mail->Port = $puecor;                                    // TCP port to connect to
	
	                                 // TCP port to connect to


    //Recipients
    $mail->setFrom($coremp, $nomcom);          //This is the email your form sends From
    $mail->addAddress($corcli2, $dsccli); // Add a recipient address
    //$mail->addAddress('contact@example.com');               // Name is optional
    //$mail->addReplyTo('info@example.com', 'Information');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    //Attachments
	 $mail->AddAttachment('../FE/notaCredito/crt/comprobantes/'.$numcomp.'.xml');  
	$mail->AddAttachment('../FE/notaCredito/crt/NC_pdf/NC'.$numcomp.'.pdf');  
	$mail->AddAttachment('../FE/notaCredito/crt/mensajes/mns-'.$cdgclave.'.xml');  
	
	
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTM  
    $mail->Subject = 'Nota Credito Electronica '.$nomcom;
	$mail->AltBody = 'Nota Credito Electronica'; // optional - MsgHTML will create an alternate automatically  
	$mail->MsgHTML('Saludos ' .$dsccli .' Adjunto encontrara su Nota de Credito Electronica ');
	// $mail->MsgHTML(file_get_contents('contents.html'));
	

    $mail->send();
    echo 'Correo 2 enviado a '.$corcli2.' de Forma Exitosa ';
	
} catch (Exception $e) {
   echo 'Error en el envio.';
    echo 'Detalle: ' . $mail->ErrorInfo;
}
	
	}
	
	
				$corcli_1 = substr($corcli, -6); 
				$corcli_2 = substr($corcli2, -6); 
				
				 $corcli_colono1 = substr($corcli, -15); 
				$corcli_colono2 = substr($corcli2, -15); 
				
				$corcli_palmatica1 = substr($corcli, -13); 
				$corcli_palmatica2 = substr($corcli2, -13); 
				//palmatica.com
				
				  echo "<BR>";
			//	grupocolono.com

 if ( ($corcli_1== ".go.cr" ) OR ($corcli_2== ".go.cr") OR ($corcli_colono1== "grupocolono.com")  OR ($corcli_colono2== "grupocolono.com") OR ($corcli_palmatica1== "palmatica.com") OR ($corcli_palmatica2== "palmatica.com") )   { 
	  // 	 if ( ($corcli_1== ".go.cr" ) OR ($corcli_2== ".go.cr") )   {   
		 
		 
	//if ($CEDCLI=="4000042139"){ // hace el envío al correo especial del ice 
	
	  /////////////////////////////////////////////////  INICIO DEL SEGUNDO  CORREO //////////////////////////////////////////

 // Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function


$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
   $mail->SMTPDebug = 2;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = $sercor;                  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = $coremp;             // SMTP username
    $mail->Password = $clacor;                          // SMTP password
    $mail->SMTPSecure = $segcor;                            // Enable SSL encryption, TLS also accepted with port 465
    $mail->Port = $puecor;                                    // TCP port to connect to
	
	                                 // TCP port to connect to


    //Recipients
    $mail->setFrom($coremp, $nomcom);          //This is the email your form sends From
    $mail->addAddress($corcli3, $dsccli); // Add a recipient address
    //$mail->addAddress('contact@example.com');               // Name is optional
    //$mail->addReplyTo('info@example.com', 'Information');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    //Attachments
	 $mail->AddAttachment('../FE/notaCredito/crt/comprobantes/'.$numcomp.'.xml');  
	$mail->AddAttachment('../FE/notaCredito/crt/NC_pdf/NC'.$numcomp.'.pdf');  
	$mail->AddAttachment('../FE/notaCredito/crt/mensajes/mns-'.$cdgclave.'.xml');  
	
	
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $mail->isHTML(true);                                  // Set email format to HTM  
    $mail->Subject = 'Nota Credito Electronica '.$nomcom;
	$mail->AltBody = 'Nota Credito Electronica'; // optional - MsgHTML will create an alternate automatically  
	$mail->MsgHTML('Saludos ' .$dsccli .' Adjunto encontrara su Nota de Credito Electronica  CORREO # 1: ' .$corcli .'  CORREO # 2: '.$corcli2);
	// $mail->MsgHTML(file_get_contents('contents.html'));
	

    $mail->send();
    echo 'Correo 3 enviado a '.$corcli3.' de Forma Exitosa ';
	
} catch (Exception $e) {
   echo 'Error en el envio.';
    echo 'Detalle: ' . $mail->ErrorInfo;
}
	
	}
	
	
	
	
		}
?>

</body>
</html>
