-1

I don't know if you know whmcs, well I'm making a basic module that in the client's product if he clicks on turn on, turn off, or restart, this sends an email to an administrator so that he can manually execute the order. .. the problem I have is that I can't get the mail to be sent, the client panel function is already working, but apparently it's an error that I can't see, I'm using PHPMailer....

This is in modules/servers/

It handles 3 main files, 1 whmcs.json which gives it the name and the phpmailer folder

servermanagement.php https://codeshare.io/OdQAeP

    <?php
if (!defined("WHMCS")) {
    die("This file cannot be accessed directly");
}

function servermanagement_MetaData() {
    return array(
        'DisplayName' => 'Gestion de Servidor Dedicado',
        'APIVersion' => '1.1',
    );
}

function servermanagement_ConfigOptions() {
    return array();
}

function servermanagement_ClientArea($params) {
    $htmlOutput = '<style>
        .action-button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 5px;
            cursor: pointer;
            border-radius: 5px;
        }
        .action-button:hover {
            background-color: #0056b3;
        }
    </style>';

    $htmlOutput .= '<form id="action-form">
        <button type="button" class="action-button" data-action="apagar">Apagar</button>
        <button type="button" class="action-button" data-action="reiniciar">Reiniciar</button>
        <button type="button" class="action-button" data-action="encender">Encender</button>
        <button type="button" class="action-button" data-action="cambiar_ptr">Cambiar PTR</button>
    </form>';

    $htmlOutput .= '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            var buttons = document.querySelectorAll(".action-button");
            buttons.forEach(function(button) {
                button.addEventListener("click", function() {
                    var action = button.getAttribute("data-action");
                    performAction(action);
                });
            });

            function performAction(action) {
                Swal.fire({
                    title: "Confirmar accion",
                    text: "¿Estas seguro que deseas realizar esta accion?",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#3085d6",
                    cancelButtonColor: "#d33",
                    confirmButtonText: "Si, realizar accion"
                }).then((result) => {
                    if (result.isConfirmed) {
                        var formData = new FormData();
                        formData.append("action", action);

                        var xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function() {
                            if (xhr.readyState === XMLHttpRequest.DONE) {
                                if (xhr.status === 200) {
                                    var response = JSON.parse(xhr.responseText);
                                    if (response.success) {
                                        Swal.fire("Exito", response.message, "success");
                                    } else {
                                        Swal.fire("Error", response.message, "error");
                                    }
                                }
                            }
                        };
                        xhr.open("POST", "modules/servers/servermanagement/servermanagement_action.php", true);
                        xhr.send(formData);
                    }
                });
            }
        });
    </script>';

    return $htmlOutput;
}
?>

functions.php https://codeshare.io/vw9r4W

    <?php
function sendAdminEmail($email, $action, $clientDetails) {
    require_once __DIR__ . '/phpmailer/src/PHPMailer.php';
    require_once __DIR__ . '/phpmailer/src/SMTP.php';
    require_once __DIR__ . '/phpmailer/src/Exception.php';

    $subject = "Solicitud de Gestion de Servidor - Accion: $action";
    $message = "El cliente {$clientDetails['fullname']} ({$clientDetails['email']}) solicito la accion '$action' en el servidor {$clientDetails['serverhostname']}.";

    $mail = new PHPMailer\PHPMailer\PHPMailer();

    try {
        // Configurar servidor SMTP
        $mail->isSMTP();
        $mail->Host = 'mail.dominio.com'; // Cambia esto al servidor SMTP que uses
        $mail->SMTPAuth = true;
        $mail->Username = 'servidores@dominio.com'; // Cambia esto a tu dirección de correo electrónico
        $mail->Password = '123456';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 465;

        // Configurar remitente y destinatario
        $mail->setFrom('servidores@dominio.com', 'Nombre Remitente'); // Cambia esto a tu información de remitente
        //$mail->addAddress($mail);
        $mail->addAddress('dominio@hotmail.com', 'name');

        // Configurar contenido del correo
        $mail->Subject = $subject;
        $mail->Body = $message;

        // Enviar correo
        $mail->send();
    } catch (Exception $e) {
       echo 'Error en el envío de correo: ' . $mail->ErrorInfo;
    }
}
?>

y el archivo servermanagement_action.php https://codeshare.io/YLoBlY

    <?php
require_once __DIR__ . '/../../../init.php';
require_once __DIR__ . '/servermanagement.php';
require_once __DIR__ . '/functions.php';

$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action) {
    $clientId = (int) $_SESSION['uid'];

    // Obtener detalles del cliente usando la API de WHMCS
    $command = 'GetClientsDetails';
    $postData = array(
        'clientid' => $clientId,
        'stats' => false,
    );
    $adminUsername = 'usernameadmin'; // Cambia esto al nombre de usuario del administrador WHMCS

    $clientDetails = localAPI($command, $postData, $adminUsername);

    $email = 'dominio@hotmail.com'; // Cambia esto a la dirección de correo electrónico deseada

    sendAdminEmail($email, $action, $clientDetails);

    header('Content-Type: application/json');
    echo json_encode(array('success' => true, 'message' => "La acción '$action' en el servidor {$clientDetails['serverhostname']} ha sido realizada con éxito."));
} else {
    header('Content-Type: application/json');
    echo json_encode(array('success' => false, 'message' => 'Acción inválida'));
}
?>

I hope you can help me, the only thing missing is for the mailing to work I don't know if I'm doing something else wrong

  • Related: https://stackoverflow.com/questions/24644436/php-mail-function-doesnt-complete-sending-of-e-mail?rq=2 – Tangentially Perpendicular Aug 06 '23 at 05:59
  • There's no reason to code your own `sendAdminEmail()` function - you can use WHMCS' API for that: https://developers.whmcs.com/api-reference/sendadminemail/ – Dennis Aug 09 '23 at 21:31

0 Answers0