PHP and Javascript - Sending HTML attachment in email

0

I created a function on my client's website that issues an event certificate and sends it via email. How the function is at the moment:

private static function setLayoutCertificado(){
    class_exists('Email') || include_once LIBRARY_CLASS_PATH . 'Email.class.php';

    $assunto = "Certificado de evento externo do colaborador " . $_SESSION['usuario']['nome'];
    $layout  = '<html>
<body>
<div id="folhaA4paisagem">
<div id="logoPrograma" style="text-align: center">
    <img id="imgPrograma" style="width: 400px" src="http://meusite.com.br/protected/viewc/theme/site/img/common/img/logo_quagilidade_original.png"/></div><divid="textoCertificado" style="text-align: center; font-family: Trebuchet MS; font-size: 24px; width: 1000px; position: fixed; top: 40%; left: 50%; transform: translate(-50%, -50%); line-height: 1.3;">
    Certificamos que o(a) colaborador(a) '.$_SESSION['usuario']['nome'].' participou da capacitação '.str_replace("'","",$_SESSION['eventoCert']).', com carga-horária de '.str_replace("'","",$_SESSION['cargaCert']).', realizado no dia '.str_replace("'","",$_SESSION['dataCert']).'. 
</div>
<div id="assinaturas" style="text-align: center; font-family: Trebuchet MS; font-size: 10px; width: 1000px; position: fixed; top: 70%; left: 50%; transform: translate(-50%, -50%);">
    <table id="tableAssinaturas" style="text-align: center; align: center; position: fixed; top: 70%; left: 50%; transform: translate(-50%, -50%);">
        <tr>
            <td>___________________________________</td>
            <td style="min-width: 300px"></td>
            <td>___________________________________</td>
        </tr>
        <tr>
            <td>Nome 1</td>
            <td></td>
            <td>Nome 2</td>
        </tr>
        <tr>
            <td>Cargo 1</td>
            <td></td>
            <td>Cargo 2</td>
        </tr>
    </table>
</div>
<div id="logo" style="text-align: center; width: 1000px; position: fixed; top: 90%; left: 50%; transform: translate(-50%, -50%);">
    <img src="http://meusite.com.br/protected/viewc/theme/site/img/common/img/logo_grande.png" />
</div>
</div>
</body>
</html>';

    $o_email = New Email();
    $o_email->to = '[email protected]';
    $o_email->subject = $assunto;
    $o_email->content = $layout;
    $o_email->sendSmtp(SMTPHOST, SMTPUSER, SMTPPASSWORD);
}

What I wanted to do was turn this HTML code into an attachment (with the same HTML extension) of that email, because what comes out in the body of the email is not very good. How can I do this?

    
asked by anonymous 12.12.2016 / 13:13

1 answer

1

First is this class I did based on some functions I found on the internet in 2012:

EmailAuthenticator.php

<?
class EmailAuthenticator
{

var $conn;
var $user;
var $pass;
var $debug;
var $boundary;

function __construct($host)
{
    $this->boundary= "XYZ-" . date("dmYis") . "-ZYX";
    $this->conn = fsockopen($host, 25, $errno, $errstr, 30);
    $this->Put("EHLO $host");
}

function Auth()
{
    $this->Put("AUTH LOGIN");
    $this->Put(base64_encode($this->user));
    $this->Put(base64_encode($this->pass));
}

function addFile($corpo_mensagem, $arr_arquivo)
{
    $arquivo_path = $arr_arquivo["path"];
    $arquivo_type = $arr_arquivo["type"];
    $arquivo_name = $arr_arquivo["name"];

    if(file_exists($arquivo_path))
    {
        // Nesta linha abaixo, abrimos o arquivo enviado.
        $fp = fopen($arquivo_path,"rb"); 
        // Agora vamos ler o arquivo aberto na linha anterior
        $anexo = fread($fp,filesize($arquivo_path));            
        // Codificamos os dados com MIME para o e-mail 
        $anexo = base64_encode($anexo);
        // Fechamos o arquivo aberto anteriormente
        fclose($fp); 
        // Nesta linha a seguir, vamos dividir a variável do arquivo em pequenos pedaços para podermos enviar
        $anexo = chunk_split($anexo);
        // Nas linhas abaixo vamos passar os parâmetros de formatação e codificação, juntamente com a inclusão do arquivo anexado no corpo da mensagem.
        $this->msg = "--".$this->boundary."\n"; 
        $this->msg.= "Content-Transfer-Encoding: 8bits\n"; 
        $this->msg.= "Content-Type: text/html; charset=\"ISO-8859-1\"\n\n";
        $this->msg.= "$corpo_mensagem\n"; 
        $this->msg.= "--".$this->boundary."\n"; 
        $this->msg.= "Content-Type: ".$arquivo_type."\n";  
        $this->msg.= "Content-Disposition: attachment; filename=\"".$arquivo_name."\"\n";  
        $this->msg.= "Content-Transfer-Encoding: base64\n\n";  
        $this->msg.= "$anexo\n";  
        $this->msg.= "--".$this->boundary."--\r\n"; 
    }
}


function Send($to, $from, $subject, $msg, $arr_arquivo=null){
    $this->msg = $msg;

    $this->Auth();
    $this->Put("MAIL FROM: " . $from);
    $this->Put("RCPT TO: " . $to);
    $this->Put("DATA");

    if($arr_arquivo!=null)
    {
        $this->addFile($msg, $arr_arquivo);
        $this->Put($this->toHeaderWithAttachment($to, $from, $subject, $this->boundary));
    }
    else
    {
        $this->Put($this->toHeader($to, $from, $subject));
    }

    $this->Put("\r\n");
    $this->Put($this->msg);
    $this->Put(".");
    $this->Close();
    if(isset($this->conn))
    {
        return true;
    }else{
        return false;
    }
}

function Put($value)
{
    return fputs($this->conn, $value . "\r\n");
}

function toHeader($to, $from, $subject)
{
    $header  = "Message-Id: <". date('YmdHis').".". md5(microtime()).".". strtoupper($from) ."> \r\n";
    $header .= "From: <" . $from . "> \r\n";
    $header .= "To: <".$to."> \r\n";
    $header .= "Subject: ".$subject." \r\n";
    $header .= "Date: ". date('D, d M Y H:i:s O') ." \r\n";
    $header .= "X-MSMail-Priority: High \r\n";
    $header .= "Content-Type: Text/HTML";
    return $header;
}

function toHeaderWithAttachment($to, $from, $subject, $boundary){
    $header = "Message-Id: <". date('YmdHis').".". md5(microtime()).".". strtoupper($from) ."> \r\n";
    $header = "MIME-Version: 1.0\n";  
    $header.= "From: $from\r\n";
    $header.= "To: $to\r\n";
    $header.= "Reply-To: $from\r\n";
    $header.= "Subject: ".$subject." \r\n";
    $header.= "Date: ". date('D, d M Y H:i:s O') ." \r\n";
    $header.= "Content-type: multipart/mixed; boundary=\"$boundary\"\r\n";  
    $header.= "$boundary\n"; 
    return $header;
}

function Close()
{
    $this->Put("QUIT");
    if($this->debug == true)
    {
        while (!feof ($this->conn)) 
        {
            fgets($this->conn) . "<br>\n";
        }
    }
    return fclose($this->conn);
}

}
?>

Then there is this file here that uses the class:

send_authenticated_with_anexchange.php

<?
error_reporting(E_ALL);
include ("EmailAuthenticator.php");

$from = "[email protected]";
$to =   "[email protected]";
$subject = "Teste da classe que envia e-mail autenticado com anexo";

// Aqui abaixo, vamos colocar o corpo da mensagem, como vamos utilizar padrão HTML, teremos de utilizar tags HTML abaixo
$corpo_mensagem = "<html>
<head>
   <title>Teste de Envio</title>
</head>
<body>
<font face=\"Arial\" size=\"2\" color=\"#333333\">
<br />
<b>Olá mundo!!</b> <br />
Este é mais um teste da <b>classe</b> que envia e-mail autenticado com anexo.
</font>
</body>
</html>";

$arquivo_path=$_FILES["meuarquivo"]["tmp_name"]; //caminho do arquivo 
$arquivo_name=$_FILES["meuarquivo"]["name"]; //nome correto do arquivo com a extensão correta
$arquivo_type=$_FILES["meuarquivo"]["type"]; //tipo do arquivo

$arr_arquivo = array( "path" => $arquivo_path, 
                      "name" => $arquivo_name,
                      "type" => $arquivo_type );

// Envio Autenticado

$host = "mail.seuservidor.com.br";
$smtp = new EmailAuthenticator($host);
$smtp->user = "[email protected]";            /* usuario do servidor SMTP */
$smtp->pass = "suasenha";                               /* senha do usuario do servidor SMTP */
$smtp->debug =true; 

if( $smtp->Send($to, $from, $subject, $corpo_mensagem, $arr_arquivo) )
{
    echo "ok";
}
else
{
    echo "error";
}
?>

And lastly there is this form that makes the post of a file (to test with any file in an easy way, but you can then change the part that calls $ _FILES in the file above where your file is on the server):

form.html

<html>
<body>
    <form method="post" enctype="multipart/form-data" action="envia_autenticado_com_anexo.php">
        <input type="file" name="meuarquivo" />
        <input type="submit" value="Enviar" />
    </form>
</body>
</html>

If this code has been useful, give it a morale and click on the little set up to give me reputation points. If you find this answer appropriate and it solves your problem, if you check it as answered you will also be giving me reputation points.

Valew, falow, hugs. :)

Any questions post here in the reply comments.

    
13.12.2016 / 21:25