PHPMailer, send html file with image and external css as message

0

I'm using the following code to send an HTML email with an attachment (zip) and if it works.

What I want is to make changes for:
1. Send an HTML template already pre-made containing CSS (it's in an external file).
2. Embed (not attach) any image in the message.
3. Send to several recipients at the same time.

<?php
    date_default_timezone_set('Etc/UTC');
    require 'PHPMailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->CharSet = 'UTF-8';
    $mail->SMTPDebug = 0;
    $mail->Debugoutput = 'html';
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;
    $mail->SMTPOptions = array(
        'ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true)
    );
    $mail->Username = "[email protected]";
    $mail->Password = "mipassword";
    $mail->setFrom('[email protected]', 'No responder');
    $mail->Subject = 'Probando mensaje';
    $mail->Body = "<h1>Mensaje HTML</h1><br><br>desde PHPMailer<br>";
    $mail->AltBody = 'No se para que sirve';
    $mail->addAttachment('adjuntar/paquete.zip');
    $mail->addAddress('[email protected]', 'Nombre Destinatario');
    if (!$mail->send()) {
        echo "Error al enviar: " . $mail->ErrorInfo;
    } else {
        echo "¡Mensaje enviado!";
    }
?>
    
asked by Jorny 29.04.2017 в 13:48
source

3 answers

3

Here is the code to send an email with PHPMailer, this allows:
1. Sending from Localhost
2. HTML Message with CSS and Embedded Images
3. Supports Tildes and Eñes (UTF-8)
4. Attached File
5. Multiple recipients

Folder structure

- www, contains index.php and enviacor.php.
- PHPMailer, PHP mailer library, download it from this link .
- Template, contains message1.html and style.css.
- Uploads, temporary uploads folder.

index.php: contains the form for the message

<!DOCTYPE html>
<html>
<head>
    <title>Enviar correo HTML+CSS+Imagen+Adjunto desde Localhost</title>
</head>
<body>
    <form method="POST" action="enviacor.php" enctype="multipart/form-data">
        <label>Destinatarios</label><br>
        <input type="text" style="width: 500px;" name="txtDestin" value="[email protected], [email protected]"><br>
        <label>Asunto</label><br>
        <input type="text" style="width: 500px;" name="txtAsunto" value = "Probando mensaje HTML"><br>
        <label>Mensaje HTML</label><br>
        <textarea name="txtMensa" style="width: 500px; height: 150px;"></textarea><br>
        <label>Imagen en el mensaje</label><br>
        <input type="file" name="txtImagen" accept="image/x-png,image/gif,image/jpeg"><br>
        <label>Archivo adjunto</label><br>
        <input type="file" name="txtAdjun" accept=".zip"><br>
        <input type="submit" value="Enviar">
    </form>
</body>
</html>

enviacor.php: send the email with the form data

<?php
    function SubirArchivo ($sfArchivo){
        $dir_subida = 'subidas/';
        $fichero_subido = $dir_subida . basename($_FILES[$sfArchivo]['name']);
        if (move_uploaded_file($_FILES[$sfArchivo]['tmp_name'], $fichero_subido)) {
            return $fichero_subido;
        } else {
            return "";
        }
    }

    set_time_limit(0);
    ignore_user_abort(true);
    /*RECOGER VALORES ENVIADOS DESDE INDEX.PHP*/
    $sDestino = $_POST['txtDestin'];
    $sAsunto = $_POST['txtAsunto'];
    $sMensaje = $_POST['txtMensa'];
    $sImagen = SubirArchivo('txtImagen');
    $sAdjunto = SubirArchivo('txtAdjun');

    date_default_timezone_set('Etc/UTC');
    require 'PHPMailer/PHPMailerAutoload.php';
    /*CONFIGURACIÓN DE CLASE*/
        $mail = new PHPMailer;
        $mail->isSMTP(); //Indicar que se usará SMTP
        $mail->CharSet = 'UTF-8';//permitir envío de caracteres especiales (tildes y ñ)
    /*CONFIGURACIÓN DE DEBUG (DEPURACIÓN)*/
        $mail->SMTPDebug = 0; //Mensajes de debug; 0 = no mostrar (en producción), 1 = de cliente, 2 = de cliente y servidor
        $mail->Debugoutput = 'html'; //Mostrar mensajes (resultados) de depuración(debug) en html
    /*CONFIGURACIÓN DE PROVEEDOR DE CORREO QUE USARÁ EL EMISOR(GMAIL)*/
        $mail->Host = 'smtp.gmail.com'; //Nombre de host
        // $mail->Host = gethostbyname('smtp.gmail.com'); // Si su red no soporta SMTP sobre IPv6
        $mail->Port = 587; //Puerto SMTP, 587 para autenticado TLS
        $mail->SMTPSecure = 'tls'; //Sistema de encriptación - ssl (obsoleto) o tls
        $mail->SMTPAuth = true;//Usar autenticación SMTP
        $mail->SMTPOptions = array(
            'ssl' => array('verify_peer' => false,'verify_peer_name' => false,'allow_self_signed' => true)
        );//opciones para "saltarse" comprobación de certificados (hace posible del envío desde localhost)
    //CONFIGURACIÓN DEL EMISOR
        $mail->Username = "[email protected]";
        $mail->Password = "mipassword";
        $mail->setFrom('[email protected]', 'Jorny');

    //CONFIGURACIÓN DEL MENSAJE, EL CUERPO DEL MENSAJE SERA UNA PLANTILLA HTML QUE INCLUYE IMAGEN Y CSS
        $mail->Subject = $sAsunto; //asunto del mensaje
        //incrustar imagen para cuerpo de mensaje(no confundir con Adjuntar)
            $mail->AddEmbeddedImage($sImagen, 'imagen'); //ruta de archivo de imagen
        //cargar archivo css para cuerpo de mensaje
            $rcss = "plantilla/estilo.css";//ruta de archivo css
            $fcss = fopen ($rcss, "r");//abrir archivo css
            $scss = fread ($fcss, filesize ($rcss));//leer contenido de css
            fclose ($fcss);//cerrar archivo css
        //Cargar archivo html   
            $shtml = file_get_contents('plantilla/mensaje1.html');
        //reemplazar sección de plantilla html con el css cargado y mensaje creado
            $incss  = str_replace('<style id="estilo"></style>',"<style>$scss</style>",$shtml);
            $cuerpo = str_replace('<p id="mensaje"></p>',$sMensaje,$incss);
        $mail->Body = $cuerpo; //cuerpo del mensaje
        $mail->AltBody = '---';//Mensaje de sólo texto si el receptor no acepta HTML

    //CONFIGURACIÓN DE ARCHIVOS ADJUNTOS 
        $mail->addAttachment($sAdjunto);

    //CONFIGURACIÓN DE RECEPTORES
        $aDestino = explode(",",$sDestino);
        foreach ( $aDestino as $i => $sDest){
            $mail->addAddress(trim($sDest), "Destinatario ".$i+1);
        }
    //ENVIAR MENSAJE
    if (!$mail->send()) {
        echo "Error al enviar: " . $mail->ErrorInfo;
    } else {
        echo "Mensaje enviado correctamente";
        //eliminar archivos temporales de carpeta subidas
        unlink($sImagen);
        unlink($sAdjunto);
    }
?>

message1.html: message template

<!DOCTYPE html>
<html>
<head>
    <title> Mensaje HTML </title>
    <style id="estilo"></style>
</head>
<body>
    <H1>Este es un mensaje HTML+CSS+IMAGEN+ADJUNTO</H1><br>
    <p id="mensaje"></p><br>
    <img src="cid:imagen" height="100px" width="100px">
</body>
</html>

style.css

h1 {
    color:#ff0000;
}
p {
    color:#0000ff;
}

PROOF OF SUBMISSION

IN TRAY

THE MESSAGE

    
answered by 29.04.2017 / 13:48
source
0

Hello good day what I have done is that in the same file to send I put the code of the template storing it in a variable in this way:

$content = '<html>';
$content .= '<head>' ;
$content .= '<style>';
$content .= '.h1{ padding-top:40px; padding-left:250px; padding-bottom:10px;}';
$content .= '.h2{ font-style: italic;  font-size:25px; padding-left: 360px; padding-top:0px;  position:absolute; whith:10px; }';
$content .= '.tel{padding-left:250px; padding-top:60px;}';
$content .= 'h1 { color:green; font-style: italic; font-size:30px ;}';
$content .= 'td {  border: black 1px solid}';
$content .= '.tdr { text-align:left; }';

$content .= '.td { text-align:center; padding-left:100px; padding-right:100px;  padding-top: 2px; padding-bottom: 2px; border-color: black; }';
$content .= '.td1 { background-color:white; border-color:white; padding-left:30px;padding-right:30px; }';
$content .= '.td2 { border-color: white; padding:15px; padding-top:5px; }';
$content .= '.td3 { background-color:white; border-color:white; padding-left:60px;padding-right:60px; }';
$content .= '.td4 { padding-left:60px;padding-right:60px; border-color: white; padding-top:10px; padding-bottom:10px;}';
$content .= '.table1 { text-align:center; border:0px solid black; padding:1px; position:relative; top:80px;left:10px;}';
$content .= '.table2 { border:1px solid black; padding:1px; position:relative; top:80px;left:10px;border-collapse: collapse;}';
$content .= '.table3 { text-align:center; border:0px solid black; padding:1px; position:relative; top:100px;left:10px;}';



$content .= '</style>';
$content .= '</head><body>';


$content .= '<table class="table1"> <tr>';puedes concatenar asi las variables como la de asunto
$content .= '<td class="td1">Asunto: '.$asunto.'</td></tr>';
All this variable you send with the function $ mail- > MsgHTML ($ content); < ----- I hope it serves you     
answered by 29.04.2017 в 15:46
-1
<!DOCTYPE html>

         PHPMailer - GMail SMTP test

// We create a new instance $ mail = new PHPMailer ();

// We activate the SMTP service $ mail-> isSMTP (); // Activate / Deactivate the SMTP "debug" // 0 = Off // 1 = Customer Message // 2 = Message from Client and Server $ mail-> SMTPDebug = 2;

// Log of SMTP debug in HTML format $ mail- > Debugoutput = 'html';

// SMTP server (for this example we use gmail) $ mail- > Host = 'smtp.gmail.com';

// SMTP port $ mail-> Port = 587;

// SSL encryption type is no longer used TSL is recommended $ mail-> SMTPSecure = 'tls';

// If we need to authenticate $ mail-> SMTPAuth = true;

// User of the email from which we want to send, for Gmail remember to use the full user ([email protected]) $ mail- > Username="[email protected]";

// Password $ mail- > Password="learnprogram";

// We connect to the database $ db = new mysqli ('hostname', 'user', 'cotraseña', 'database');

if ($ db- > connect_errno > 0) {     die ('Impossible to connect ['. $ db-> connect_error. ']'); }

// We create the SQL statements $ result = $ db- > query ("SELECT * FROM people");

// We started the "loop" to send multiple emails.

while ($ row = $ result->> fetch_assoc ()) {     // We add the address of the person sending the email, in this case Codejobs, first the email, then the name of the sender.

$mail->setFrom('[email protected]', 'CodeJobs!'); 
$mail->addAddress($row['PersonasEmail'], $row['PersonasNombre']); 

//La linea de asunto 
$mail->Subject = 'Bienvenido a Codejobs!'; 

// La mejor forma de enviar un correo, es creando un HTML e insertandolo de la siguiente forma, PHPMailer permite insertar, imagenes, css, etc. (No se recomienda el uso de Javascript) 

$mail->msgHTML(file_get_contents('contenido.html'), dirname(__FILE__)); 

// Enviamos el Mensaje 
$mail->send(); 

// Borramos el destinatario, de esta forma nuestros clientes no ven los correos de las otras personas y parece que fuera un único correo para ellos. 
$mail->ClearAddresses(); 

}
? >

Dear, check this link, Send massive or simple emails with PHP, MySQLi and PHPMailer

    
answered by 30.04.2017 в 23:53