PHP: Como enviar emails

Palavras-chave: PHP, enviar, e-mail, email, gmail, evolution

Uma das coisas mais chatas em PHP é enviar email. Não por causa do PHP, mas porque cada software cliente de email trata os headers de uma maneira diferente.

Passei uma madrugada dessas quebrando a cabeça, porque os emails funcionavam no Evolution, mas não no Gmail. Depois funcionavam no Gmail, mas não no Evolution. Quando consegui fazer funcionar nos dois, empacotei tudo numa classe.

E aí está, para ajudar outros a não quebrarem a cabeça :-)

<?php
/*
 * Classe Mail
 * para envio de emails
 */
class Mail
{
    private $parts;

    /*
     * Método construtor
     */
    function __construct()
    {
        $this->parts = array();
        $this->boundary = md5(time());
    }

    /*
     * Adiciona HTML
     */
    function addHtml($body)
    {
        $body = stripslashes($body);
        $msg  = "--{$this->mime_boundary}\\n";
        $msg .= "Content-Type: text/html; charset=ISO-8859-1\\n\\n";
        $msg .= $body;

        $this->parts[] = $msg;
    }

    /*
     * Adiciona Texto
     */
    function addText($body)
    {
        $body = stripslashes($body);
        $msg  = "--{$this->mime_boundary}\\n";
        $msg .= "Content-Type: text/plain; charset=ISO-8859-1\\n\\n";
        $msg .= $body;

        $this->parts[] = $msg;
    }

    /*
     * Adiciona Imagem
     */
    function addPng($filename, $download)
    {
        $fd=fopen($filename, 'rb');
        $contents=fread($fd, filesize($filename));
        $contents=chunk_split(base64_encode($contents),68,"\\n");
        fclose($fd);

        $msg  = "--{$this->mime_boundary}\\n";
        $msg .= "Content-Type: image/png; name={$download}\\n";
        $msg .= "Content-Transfer-Encoding: base64\\n";
        $msg .= "Content-Disposition: attachment; filename={$download}\\n\\n";
        $msg .= "{$contents}";

        $this->parts[] = $msg;
    }

    /*
     * Envia Email
     */
    function send($from, $to, $subject)
    {
        $headers  = "From: {$from}\\n";
        $headers .= 'Content-Type: multipart/mixed; boundary="'.$this->mime_boundary."\"\\n";
        $headers .= 'X-Mailer: PHP-' . phpversion() . "\\n";
        $headers .= "Mime-Version: 1.0\\n\\n";

        $msg = implode("\\n", $this->parts);

        mail($to, $subject, $msg, $headers);
    }
}
?>
This entry was posted in PHP. Bookmark the permalink.

9 Responses to PHP: Como enviar emails

  1. Marcos Bezerra says:

    Perfeita essa classe. Já a adicionei em meu framework. Parabéns.

  2. Guilherme says:

    Ou você pode evitar reinventar a roda e usar o Mail_Mime do PEAR, que é mais robusto.

    http://pear.php.net/manual/en/package.mail.mail-mime.example.php

  3. Pingback: rascunho » Seção de dados do blog » links for 2006-12-28

  4. Elomar says:

    Parabéns pela classe. Vai ajudar bastante…

  5. André Taiar says:

    Não funciona pro Outlook…

  6. Nuno says:

    Isso dá pra adicionar attachments? Ou só imagens dentro do mail a enviar?

  7. Joao says:

    funciona pra Globo.com?

    Porque eu utilizei a função normal mail() do php sem tantas especificações no headers, e o único que não recebeu foi o e-mail da Globo.

    Aguardo notícias,

    Grato.

  8. cock rings says:

    Great paintings! That is the kind of information that are supposed to be shared around the net. Shame on the search engines for no longer positioning this post upper! Come on over and talk over with my site . Thank you =)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>