Script SMTP para VPS & Hosting

En este nuevo tutorial te mostraremos un script SMTP de ejemplo, el cual podrás implementar en tus websites alojados en Hostings o en VPS.

Describiremos primero cada parte del código para luego brindarte el código de ejemplo completo. Podrás adaptar este código según lo prefieras y de acuerdo con la parametrización te exija tu implementación, pero hay instrucciones excluyentes que deberás mantener para que funcione eficientemente.

La versión de phpmailer actual requiere incluir instrucciones para verificar el certificado y realiza comprobaciones para saber cuándo aplicar STARTTLS. Se soluciona con el siguiente código y utilizando como host SMTP a localhost:

$mail->Host = "localhost";  
if (version_compare(PHP_VERSION, '5.6.0') >= 0) {
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true,
        ),
    );
}

En el caso de que necesitesctivar el debugger para depurar el código, podrás activar esta instrucción quitándole los símbolos ‘//’:

//$mail->SMTPDebug = 3;

Luego:

$mail->Host = 'localhost;smtp2.example.com';  // 

En este caso, el nombre del servidor es localhost. Podrás añadir más nombres de hosting si lo desea, pero deberán estar separados por ;

La autenticacion debe estar en true. En cuanto a las siguientes dos instrucciones, encontramos que las ultimas versiones de phpmailer requieren no utilizar SSL. Las colocamos en ‘false’ para que no efectue encriptacion ya que utilizamos localhost.

$mail->SMTPAuth = true;                               // Enable SMTP authentication

$mail->SMTPSecure = false;
$mail->SMTPAutoTLS = false;

En username debes colocar la cuenta de correo que estas utilizando. En password debes colocar la contraseña que asignaste en tu panel de control:

$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password

Deberás desactivar el uso de certificado SSL/TLS anteponiendo los símbolos //

//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted

Utilizarás el puerto 25:

$mail->Port = 25;                                    // TCP port to connect to

En el siguiente bloque de código, tenés que configurar aspectos referentes al mensaje:

Colocá el remitente y su nombre. En la instrucción siguiente, colocá al destinatario y su nombre. El nombre es opcional.

En las ultimas líneas verás que se añaden destinatarios con copia y con copia oculta.

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

Añadí archivos adjuntos, el nombre es opcional y va a la derecha.

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

Si querés indicar que el mensaje de correo es en formato HTML:

$mail->isHTML(true);                                  // Set email format to HTML

Colocá el asunto y el cuerpo del mensaje:

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

Finalmente va el condicional que pregunta si se ha enviado el mensaje; si no fue enviado, muestra error. Si fue enviado, muestra mensaje de envío exitoso:

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Eso es todo.

A continuación, adjuntamos el script completo:

<?php
require 'PHPMailerAutoload.php';

if (version_compare(PHP_VERSION, '5.6.0') >= 0) {
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true,
        ),
    );
}

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'localhost;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'user@example.com';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                                    // TCP port to connect to

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
$mail->addAddress('ellen@example.com');               // Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

?>

Con esto finalizamos otro tutorial.

Y recordá que si tenés alguna duda, podés escribirnos a soporte@baehost.com

Hasta la próxima!

Deja una respuesta