PhpMail Como enviar PHP Mail con Autenticación

EJEMPLO SCRIPT DE PRUEBA 2018 
===============

<?php
//error_reporting(E_ALL); //Habilitar para ver errores php
//ini_set('display_errors', 1); // Habilitar para ver errores php
//require('phpmailer/PHPMailerAutoload.php');
require('/home/USUARIO/public_html/INCLUDE/phpmailer/PHPMailerAutoload.php'); // Si no funciona el comando arriba coloque la ruta DE PHPMAILER
$mail = new PHPMailer;
//$mail->SMTPDebug = 1; // Habilitar salida de Debug

$mail->IsSMTP(); // Colocar el mailer para usar SMTP
$mail->Host = 'mail.sudominio.com'; // Especificar servidor principal de backup
$mail->Port = 587; // Configurar puerto SMTP
$mail->SMTPAuth = true; // Habilitar SMTP
$mail->Username = 'prueba@sudominio.com'; // Usuario SMTP
$mail->Password = 'Prueba2018'; // Contraseña SMTP
$mail->SMTPSecure = 'tls'; // Habilitar encrypcion, 'ssl' también se acepta.

$mail->From = 'ventas@undominio.com';
$mail->FromName = 'Your From name';
$mail->AddAddress('soporte@otrosdominios.com', 'Mark S'); // Agregue un receptor
$mail->AddAddress('ventas@dominioopcional.com'); // Este nombre es opcional.

$mail->IsHTML(true); // Colocar formato de correo a HTML

$mail->Subject = 'Aquí colocas el Asunto';
$mail->Body = 'Este es el cuerpo del mensaje <strong>en Retenido!</strong>';
$mail->AltBody = 'Este es el cuerpo del mensaje para Clientes no-HTML';

if(!$mail->Send()) {
echo 'El Mensaje no pudo ser enviado.';
echo 'Error del Mailer: ' . $mail->ErrorInfo;
exit;
}

echo 'El Mensaje ha sido enviado';
?>




===============
EJEMPLO DE GITHUB

Ejemplo de Script de contacto:  Tomado de: https://github.com/PHPMailer/PHPMailer

mail.php



<?php
//
// A validated PHP contact form
// http://blog.surmodernite.de/2013/12/a-validated-php-contact-form
//
// The MIT License (MIT)
// Copyright (c) 2013 tilman.boerner@gmx.net
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// uses PHPMailer (https://github.com/PHPMailer/PHPMailer), licensed under
// LGPL 2.1 (http://www.gnu.org/licenses/lgpl-2.1.html)
function getItem($array, $key, $default = "") {
  return isset($array[$key]) ? $array[$key] : $default;
}
function okLength($str, $maxlen) {
    $len = strlen($str);
    return ($len > 0) and ($len <= $maxlen);
}
function sanitize_and_validate($data) {
    $name = getItem($data, 'name');
    $email = getItem($data, 'email');
    $message = getItem($data, 'message');
    if (! okLength($name, 100)) {
        return False;
    }
    if (! okLength($email, 100)) {
        return False;
    }
    if (! okLength($message, 2048)) {
        return False;
    }
    $name = trim($name);
    $name = filter_var($name, FILTER_SANITIZE_STRING);
    if (empty($name)) {
        return False;
    }
    $email = trim($email);
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return False;
    }
    $message = trim($message);
    $message = filter_var($message, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
    if (empty($message)) {
        return False;
    }
    $message = $name . " (" . $email . ") writes:\n\n" . $message;
    $cc = (bool) getItem($data, 'cc');
    $seems_robot = (bool) trim(getItem($data, 'subject'));
    $data = array(
        'name' => $name,
        'email' => $email,
        'message' => $message,
        'cc' => $cc,
        'seems_robot' => $seems_robot,
    );
    return $data;
}
function print_form($data) {
    $name = getItem($data, 'name');
    $email = getItem($data, 'email');
    $message = getItem($data, 'message');
    $subject = getItem($data, 'subject');
    $cc_checked = getItem($data, 'cc') ? 'checked="checked"' : '';
    $form = <<<ENDFORM
<form id="form2" action="" method="post">
  <fieldset>
    <legend>Contact form</legend>
    <p class="first">
      <label for="name">Name</label>
      <input type="text" name="name" id="name" size="30" maxlength="50" value="$name" required />
    </p>
    <p>
      <label for="email">Email</label>
      <input type="email" name="email" id="email" size="30"  maxlength="50" value="$email" required />
      <label for="cc">
          <input type="checkbox" name="cc" id="cc" $cc_checked />
          Send me a copy
      </label>
    </p>
    <p>
      <label for="message">Message</label>
      <textarea name="message" id="message" cols="30" rows="10" maxlength="1024" required>{$message}</textarea>
    </p>
    <p class="special">
      <label for="subject">Robot Catcher: Do not write into this field</label>
      <input type="text" name="subject" id="subject" size="30"  maxlength="50" value="$subject"/>
      This last field is used to catch robots. If anything is written in here,
      the message will <strong>not</strong> be sent.
    </p>
    <p class="submit"><button type="submit">Send</button></p>
  </fieldset>
</form>
<script>
    $("#form2").validate();
</script>
ENDFORM;
    echo $form;
}
function send_mail($data) {
    if ($data['seems_robot']) {
        echo <<<ENDERROR
        <div class="error">
        <h3>
            Message not sent.
        </h3><p>
            Because the &quot;Robot Catcher&quot field contains text, it
            looks like a bot filled out the form.
        </p><p>
            If you're not a bot, we apologize! Please go back to the form
            to try again, and make sure the &quot;Robot Catcher&quot field
            is empty.
        </p>
        </div>
ENDERROR;
        return True;
    }
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $DEBUG = 0;
        $HOST = 'YOUR_OUTGOING_MAILSERVER';
        $PORT = 587;
    $USER = "EMAIL_USERNAME";
    $PASSWORD = "EMAIL_PASSWORD";
    $RECIPIENT_ADDR = "EMAIL_RECIPIENT";
    $SUBJECT = 'EMAIL_SUBJECT';
    $name = $data['name'];
    $email = $data['email'];
    $message = $data['message'];
    $cc_self = $data['cc'];
    date_default_timezone_set('Etc/UTC');
    require 'PHPMailer/PHPMailerAutoload.php';
    //Create a new PHPMailer instance
    $mail = new PHPMailer();
    //Tell PHPMailer to use SMTP
    $mail->isSMTP();
    //Enable SMTP debugging
    $mail->SMTPDebug = $DEBUG;
    //Ask for HTML-friendly debug output
    $mail->Debugoutput = 'html';
    //Set the hostname of the mail server
    $mail->Host = $HOST;
    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
    $mail->Port = $PORT;
    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'tls';
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //Username to use for SMTP authentication - use full email address for gmail
    $mail->Username = $USER;
    //Password to use for SMTP authentication
    $mail->Password = $PASSWORD;
    //Set who the message is to be sent from
    // $mail->setFrom($email, $name);
    $mail->setFrom($USER);
    //Set an alternative reply-to address
    // $mail->addReplyTo('somebody@somewhere.com');
    //Set who the message is to be sent to
    $mail->addAddress($RECIPIENT_ADDR);
    $mail->addReplyTo($email, $name);
    if ($cc_self) {
        $mail->addCC($email);
    }
    //Set the subject line
    $mail->Subject = $SUBJECT;
    $mail->isHTML(true);
    $mail->Body    = nl2br(filter_var($message, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_ENCODE_HIGH));
    //Replace the plain text body with one created manually
    $mail->AltBody = $message;
    //send the message, check for errors
    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
        return False;
    } else {
        echo "<p>Message sent.</p><p>Thank you! I will get back to you as soon as possible.</p>";
        return True;
    }
}
$data = sanitize_and_validate($_POST);
if (!($data and send_mail($data))) {
    print_form($_POST);
}
?>



========================================================================================


OTRO EJEMPLO  DE SCRIPT:

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
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 = 'smtp1.example.com;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 = 587;                                    // TCP port to connect to

    //Recipients
    $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');

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

    //Content
    $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';

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


  • 1 Els usuaris han Trobat Això Útil
Ha estat útil la resposta?

Articles Relacionats

Donde puedo ver las plantillas - templates

Si desea usar el creador de sitios Web ir al Cpanel ---> Software Servicios --- >...

Cómo obtener su propio favicon - rápido

Algunos de ustedes nos han contactado para preguntarnos cómo podía conseguir una imagenpequeña a...

Redireccionar Dominio - Página con .htaccess

Creación y configuración fichero .htaccess Para añadir esta configuración será necesario crear...

Redireccionar Dominio - Página con Código html, php, Asp, javascript

Estos son algunos ejemplos de como redireccionar su dominio ó página Web usando...

PhpMail Warning: mail(/var/log/phpmail.log) [function.mail]: failed to open stream: Permission denied

El mensaje de advertencia generado por la secuencia de comandos (Script) es causada por el hecho...