Send Resume formatted with php

Asked

Viewed 178 times

0

I’m creating a form for a company to register curriculum and it’s already working, only I did to generate the resume and print, someone could tell me how it would be done so that, by clicking send, it send this file to a particular formatted email already. The code I’m using is just below.

<?php
//Captura o modelo selecionado
$modelo = $_POST['modelo'];

//Verifica se o cliente selecionou uma foto no formulário ou deixou em branco
if($_FILES['foto']['size'] > 0){
    //Obtém o conteúdo da imagem (conteúdo binário)
    $conteudo = file_get_contents($_FILES['foto']['tmp_name']);
    
    //Obtém o tipo da imagem enviada (jpg, png)
    $tipo = pathinfo($_FILES['foto']['tmp_name'], PATHINFO_EXTENSION);
    
    //Gera a imagem em base64 para poder colocar na tag <img> do curriculo
    $foto = 'data:image/' . $tipo . ';base64,' . base64_encode($conteudo);
} else {
    //Se o cliente não selecionou uma foto, usamos a imagem padrão
    $foto = "img/avatar-1.png";
}

//Gera um array com os dados a serem enviados para impressão no currículo
//Cada elemento do array recebe o valor de um campo do formulário
$dados = array(
    'foto' => $foto,
    'nome' => $_POST['nome'],
    'cargo' => $_POST['cargo'],
    'endereco' => $_POST['endereco'],
    'telefone' => $_POST['telefone'],
    'email' => $_POST['email'],
    'resumo' => $_POST['resumo'],
    'formacoes' => isset($_POST['formacao-curso']) ?
                   array(
                        'cursos' => $_POST['formacao-curso'],
                        'instituicoes' => $_POST['formacao-instituicao'],
                        'conclusoes' => $_POST['formacao-conclusao']
                    ) : null, //Se o usuário não adicionou nenhuma formação, esse elemento ficará nulo
    'experiencias' => isset($_POST['experiencia-cargo']) ? 
                      array(
                        'cargos' => $_POST['experiencia-cargo'],
                        'empresas' => $_POST['experiencia-empresa'],
                        'inicios' =>  $_POST['experiencia-inicio'],
                        'fins' =>  $_POST['experiencia-fim'],
                      ) : null //Se o usuário não adicionou nenhuma experiência, esse elemento ficará nulo
);

//Carrega o arquivo referente ao modelo de currículo selecionado
//Quando faz isso, poderemos imprimir o conteúdo da variável $dados no currículo
require_once("modelos/{$modelo}.php");

  • Samuel, you can use the Phpmailer. Look at their documentation that there is a step by step well explained.

  • I’ll take a look, thanks

  • Anything calls me I have a well-defined structure that I use for Phpmailer.

  • Boy, I’m accustomed to sending plain ones with php, but I’m not really understanding with phpmailer, if you want to give me a light there

1 answer

0


To send email with attachment, in your case a pdf, you can use the class Phpmailer, which is nothing more than a class, or rather library, which allows sending emails via connection SMTP or POP3.

Before you start follow the tutorial below:

  1. Download the latest version (in this case it is 6.0.5) of Phpmailer.

  2. Unzip the downloaded file and keep only those files together with the folder src:

    • Exception.php, Oauth.php, Phpmailer.php, POP3.php and SMTP.php;

Now let’s get down to business, sending email.

Let’s define a basic structure for our project.

/seu_projeto/
   |--app/
   |    |--class/
   |    |       |--PHPMailer/
   |    |       |            |--src/
   |    |       |            |     |Exception.php
   |    |       |            |     |OAuth.php
   |    |       |            |     |PHPMailer.php
   |    |       |            |     |POP3.php
   |    |       |            |     |SMTP.php
   |    |Mail.php

With this we can already carry out the e-mail sending script using the class Mail.php. In the example for a contact form, but sending an attachment.

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class Mail
{
    public function sendMail($name, $email, $phone, $subject, $message)
    {
        require 'PHPMailer/src/PHPMailer.php';
        require 'PHPMailer/src/SMTP.php';
        require 'PHPMailer/src/Exception.php';

        $mail = new PHPMailer();
        try {
            // Server settings
            $mail->isSMTP();                                      // Define o mail para usar o SMTP
            $mail->Host = 'smtp.dominio.net';                     // Define o host do e-mail
            $mail->SMTPAuth = true;                               // Permite autenticação SMTP 
            $mail->Username = '[email protected]';              // Conta de e-mail que enviará o e-mail
            $mail->Password = 'exemplo123';                       // Senha da conta de e-mail
            $mail->SMTPSecure = 'tls';                            // Permite encriptação TLS
            $mail->Port = 587;                                    // Porta TCP que irá se conectar
            $mail->SMTPOptions = array( // Configuração adicional, não obrigatória (caso de erro de ssl)
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            // Recipients
            $mail->setFrom('[email protected]', 'Título do e-mail, ou assunto'); // Define o remetente
            $mail->addAddress('[email protected]', 'Contato Site');             // Define o destinário

            $mail->addAttachment('/var/tmp/file.tar.gz');                         // Adicona anexos (só passar o arquivo, localização dele)

            // Content
            $mail->isHTML(true); // Define o formato do e-mail para HTML
            $mail->Subject = 'Contato feito pelo site';
            $mail->Body = "
                        <html>
                        <head>
                        </head>
                        <body>
                        <h2>Coloque aqui o seu assunto</h2>

                        <table>
                          <tr>
                            <th>Nome</th>
                            <th>E-mail</th>
                            <th>Telefone</th>
                            <th>Assunto</th>
                          </tr>
                          <tr>
                            <td>$name</td>
                            <td>$email</td>  
                            <td>$phone</td>
                            <td>$subject</td>
                          </tr>
                        </table>

                        <h2>Conteúdo da mensagem</h2>

                        <p>$message</p>

                        </body>
                        </html>";
            $mail->send(); // Envia o e-mail
            return true;
        } catch (Exception $e) { // Se capturar exceção retorna false
            return false;
        }
    }
}

Documentation of Phpmailer

Forum of Phpmailer

  • I understand what you want to do, but with 42 fields it will work?

  • 42 fields of which?

  • Opa this is another matter, I will replace the code and I will test

  • If it works remember to give a positive vote the answer and mark as the correct :)

  • Clicking send only aparace a blank screen

  • Triggers the debug: $mail->SMTPDebug = 2; and see if he shows any error - puts right at the beginning

  • blank yet

  • How is your project structure?

  • index generatCurriculo -> src -> Exception Oauth Phpmailer

  • The Mail.php class you should leave inside the generatCurriculo folder, and remember to put src inside another folder called Phpmailer. Another question, you changed the value of host, username, password right?

  • nothing yet, I changed the src directory and nothing, I’ll have to do it another way anyway. I thank you there

Show 6 more comments

Browser other questions tagged

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