Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
  • Chatbox

    Lembre-se de ler as nossas regras!
    Load More
    You don't have permission to chat.
iJhefe

Enviar E-mail com PHP e template HTML

Recommended Posts

WZgvloa.png

Fala meus bons, recentemente precisei fazer um código para enviar e-mails, que por sua vez é bem simples, no entanto quis implementar nele um sistema de template para enviar e-mails  e repostas em JSON para utilizar com Ajax.

Postei porque meu amigo @Fulano não queria que eu postasse. Beijos para ele.

 

<?php
class Mail {

    private $layout;
    private $rType = 'Ajax';
    private $headers;
    
    public $to;
    public $message;
    public $subject = 'Mensagem de Email';
    
    public function useHTML() {

        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

        $this->headers = $headers;
    }

    public function set_from($from) {
        
        $this->headers .= "From: $from \r\n";
    }

    public function set_response_type($type) {
        $this->rType =  $type;
    }

    public function set_layout_var($var) {
        $this->layout['vars'][] = $var;
    }

    public function set_layout_data($data) {
        $this->layout['data'][] = $data;
    }

    public function set_layout($method, $data) {
        
        $lt = ($method == 'file' ? 'file' : 'html');

        if ($lt == 'file') 
        {
            $d = DOCUMENT_ROOT . '/' . $data;

            $l = file_get_contents($d);
        

            if (!$l) {
                $this->res(400, 'Ocorreu um problema interno (0x0F101)');
            }

            $this->layout['model'] = $l;

            return true;

        }

        $this->layout['model'] = $data;

        return true;

    }

    private function generate_layout() {
        
        $this->layout['generated'] = str_replace($this->layout['vars'], $this->layout['data'], $this->layout['model']);

    }

    public function get_layout() {
        return $this->layout['generated'];
    }

    private function generate_message() {
        if (empty($this->layout) || is_null($this->layout))
            return $this->message;

        $this->generate_layout();
        return $this->layout['generated'];
    }

    public function send() {

        $message = $this->generate_message();

        if ( mail($this->to, $this->subject, $message, $this->headers) )
            return $this->res(200, 'E-mail enviado com sucesso');

        
        return $this->res(403, 'Não foi possível enviar o e-mail.');

    }

    private function res($code, $message) {

        $r = strtolower($this->rType);
        
        if($r == 'ajax') {

            echo json_encode(["status" => $code, 'response' => $message]);
            return true;
        }

        return json_encode(["status" => $code, 'response' => $message]);
    }

}

 

Lembrando que nesse código de cima estou utilizando uma Constate pré definida por mim, a DOCUMENT_ROOT, que é nada além da RAIZ da pasta.

No caso, o layout deve ser referenciado de acordo com a raiz do site, mas você pode mudar isso, um exemplo de uso vai abaixo.

<?php
$Mail = new Mail();
        
        $Mail->useHTML(); # Setar para usar o Header de HTML de E-mail

        # Setar o template HTML, caso não use essa função ele vai interpretar o e-mail como Mensagem comum e as funções de layout não irão funcionar.
        $Mail->set_layout('file', 'mail-templates/recover');

        // Setar as variáveis para o php interpretar

        $Mail->set_layout_var('{logoURL}');

        $Mail->set_layout_var('{user}');
        $Mail->set_layout_var('{codigo}');

        $Mail->set_layout_var('{buttonURL}');
        $Mail->set_layout_var('{buttonTXT}');

        // Setar os valores das variáveis POR ORDEM

        $Mail->set_layout_var('https://hazeforum.com/uploads/monthly_2019_04/small.png.52ed3bb48b55d1c0a766ad91482651b2.png');

        $Mail->set_layout_data('iJhefe');
        $Mail->set_layout_data('1234');

        $Mail->set_layout_data('https://hazeforum.com');
        $Mail->set_layout_data('Acesse nosso fórum');

        $Mail->to = "[email protected]"; # Para quem vai o e-mail

        $Mail->subject = 'Recuperação de Senha: Haze Fórum'; # Assunto do e-mail

        $Mail->set_from('Haze Fórum <[email protected]>'); # Opcional, seta de quem veio o e-mail.

        
        return $Mail->send();

 

Nesse caso, o arquivo Recover  está na pasta "mail-templates", na raiz do projeto. 

 

Arquivo Recover:

<!doctype html>
<html>

<head>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Soliticação de Senha</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

    <style>
        @media only screen and (max-width: 620px) {
            table[class=body] h1 {
                font-size: 28px !important;
                margin-bottom: 10px !important;
            }

            table[class=body] p,
            table[class=body] ul,
            table[class=body] ol,
            table[class=body] td,
            table[class=body] span,
            table[class=body] a {
                font-size: 16px !important;
            }

            table[class=body] .wrapper,
            table[class=body] .article {
                padding: 10px !important;
            }

            table[class=body] .content {
                padding: 0 !important;
            }

            table[class=body] .container {
                padding: 0 !important;
                width: 100% !important;
            }

            table[class=body] .main {
                border-left-width: 0 !important;
                border-radius: 0 !important;
                border-right-width: 0 !important;
            }

            table[class=body] .btn table {
                width: 100% !important;
            }

            table[class=body] .btn a {
                width: 100% !important;
            }

            table[class=body] .img-responsive {
                height: auto !important;
                max-width: 100% !important;
                width: auto !important;
            }
        }

        @media all {
            .ExternalClass {
                width: 100%;
            }

            .ExternalClass,
            .ExternalClass p,
            .ExternalClass span,
            .ExternalClass font,
            .ExternalClass td,
            .ExternalClass div {
                line-height: 100%;
            }

            .apple-link a {
                color: inherit !important;
                font-family: inherit !important;
                font-size: inherit !important;
                font-weight: inherit !important;
                line-height: inherit !important;
                text-decoration: none !important;
            }

            .btn-primary table td:hover {
                background-color: #1e53b6 !important;
            }

            .btn-primary a:hover {
                background-color: #1e53b6 !important;
                border-color: #1e53b6 !important;
                box-shadow: 0 4px 20px 0px rgba(0, 0, 0, 0.14), 0 7px 10px -5px rgba(30, 83, 182, 0.4);
            }
        }
    </style>
</head>

<body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
    <table role="presentation" border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-color: #f6f6f6; width: 100%;" width="100%" bgcolor="#f6f6f6">
        <tr>
            <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;" valign="top">&nbsp;</td>
            <td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; max-width: 580px; padding: 10px; width: 580px; margin: 0 auto;" width="580" valign="top">
                <div class="content" style="box-sizing: border-box; display: block; margin: 0 auto; max-width: 580px; padding: 10px;">

                    <!-- START CENTERED WHITE CONTAINER -->
                    <span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">Você solicitou sua senha !</span>
                    <table role="presentation" class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background: #ffffff; border-radius: 3px; width: 100%;" width="100%">

                        <!-- START MAIN CONTENT AREA -->
                        <tr>
                            <td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;" valign="top">
                                <table role="presentation" border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;" width="100%">
                                    <tr>
                                        <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;" valign="top">
                                            <center><img src="{logoURL}" style="border: none; -ms-interpolation-mode: bicubic; max-width: 100%;"></center><br><br>
                                            <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; margin-bottom: 15px;">Olá {user},</p>
                                            <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; margin-bottom: 15px; color: #AFB5C0;">Abaixo está seu código de recuperação de senha, se você não solicitou uma nova senha ignore esse e-mail .</p>
                                            <br>
                                            <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; margin-bottom: 15px;">Sua Código: <br>
                                                <font style="color: #AFB5C0; font-size: 11px;">{codigo}</font>
                                            </p><br><br>

                                            <table role="presentation" border="0" cellpadding="0" cellspacing="0" class="btn btn-primary" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; box-sizing: border-box; width: 100%;" width="100%">
                                                <tbody>
                                                    <tr>
                                                        <td align="left" style="font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;" valign="top">
                                                            <table role="presentation" border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: auto;">
                                                                <tbody>
                                                                    <tr>
                                                                        <td style="font-family: sans-serif; font-size: 14px; vertical-align: top; border-radius: 5px; text-align: center; background-color: #AFB5C0;" valign="top" align="center" bgcolor="#AFB5C0"> <a href="{buttonURL}" target="_blank" style="border: solid 1px #3498db; border-radius: 5px; box-sizing: border-box; cursor: pointer; display: inline-block; font-size: 14px; font-weight: bold; margin: 0; padding: 12px 25px; text-decoration: none; text-transform: capitalize; background-color: #AFB5C0; border-color: #AFB5C0; color: #ffffff;"><i class="far fa-eye"></i> {buttonTXT}</a> </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>

                        <!-- END MAIN CONTENT AREA -->
                    </table>

                    <!-- START FOOTER -->
                    <div class="footer" style="clear: both; margin-top: 10px; text-align: center; width: 100%;">
                        <table role="presentation" border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;" width="100%">
                            <tr>
                                <td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; color: #999999; font-size: 12px; text-align: center;" valign="top" align="center">
                                    <span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;">Copyright © 2019 • Haze Fórum <br>
                                        Todos os Direitos Reservados.
                                    </span></td>
                            </tr>
                            <tr>
                                <td class="content-block powered-by" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; color: #999999; font-size: 12px; text-align: center;" valign="top" align="center">
                                    Site: <a href="https//hazeforum.com" target="_blank" style="font-size: 12px; text-align: center; text-decoration: none; color: #1e53b6;">www.hazeforum.com</a>.
                                </td>
                            </tr>
                        </table>
                    </div>
                    <!-- END FOOTER -->

                    <!-- END CENTERED WHITE CONTAINER -->
                </div>
            </td>
            <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;" valign="top">&nbsp;</td>
        </tr>
    </table>
</body>

</html>

 

Ao template do recover, o @Fulano quem me passou.

 

Pode usar livremente, em caso de dúvidas, crie um tópico.

 

Mantenha os créditos, caso use.

Share this post


Link to post
Share on other sites

Interessante, código atualizado e organizado e dá pra implementar em qualquer site.

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×