PHP and Javascript - Sending HTML attachment in e-mail

Asked

Viewed 454 times

0

I created on my client’s website a function that issues an event certificate and sends it by email. How is the function 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>
<div id="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 HTML extension) of this email, because what comes out in the body of the email is not very good. How can I do that?

  • I’ve done this and I need to look for the code, but I think in your case it is better to try to format to go in the email even though going as an attachment most people will not even open and some email clients will increase the chances that your email is considered spam. Ultimately even a link would be better than sending as an attachment.

  • @Antonioalexandrealonsodesi Until I have no problem sending the formatting in the body of the email or the HTML code. But the problem is that when printing the certificate it is not legal to be in the body of the email, at least in Gmail. If you have the code there, thank you.

  • I’m going to answer an anti-steel example I did in 2012 of an authenticated email sending via smtp with attached file. Test and see if it helps.

1 answer

1

First there is this class I made 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’s this file here that uses the class:

envia_autenticado_com_attachment.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 finally there is this form that does 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 to where your file is on the server):

html form.

<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 a moral and click the arrow up to give me reputation points. If you find this answer appropriate and that solves your problem, if you mark it as answered you will also be giving me reputation points.

Valew, Falow, hugs. :)

Any questions post here in the reply comments.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.