Send email with attachments in php

10

I'm sending an email, everything works fine. Now I wanted to add some files as an attachment. I have the following code:

$from = $_SESSION['email_cliente'];
$email_destino = "[email protected]";
$subject = "Assunto";
$messagem = "Isto é uma mensagem enviada por php"
$headers = "From: $from <$from>\r\n".
           "MIME-Version: 1.0" . "\r\n" .
           "Content-type: text/html; charset=UTF-8" . "\r\n"; 
mail($email_destino, $subject,$message,$headers);

How can I add attachments?

    
asked by anonymous 02.04.2014 / 15:59

1 answer

17

Using the mail() function

An email is composed of a header and a body, and the body can be separated into several parts. In the standard the term used to identify the separator of these parts is boundary . So let's set a boundary to our email. The rules for generating a boundary can be found in the internet easily . But simplifying, it is nothing more than a random string that should appear in the email only when it is to indicate a part of the email.

$boundary = "XYZ-".md5(date("dmYis"))."-ZYX";

Get the information of the file you are going to attach

// Arquivo enviado via formulário
$path = $_FILES['attachment']['tmp_name']; 
$fileType = $_FILES['attachment']['type']; 
$fileName = $_FILES['attachment']['name']; 

// Ou arquivo local
$path = '/caminho/para/o/arquivo';
$fileType = mime_content_type( $path );
$fileName = basename( $path );

// Pegando o conteúdo do arquivo
$fp = fopen( $path, "rb" ); // abre o arquivo enviado
$anexo = fread( $fp, filesize( $path ) ); // calcula o tamanho
$anexo = chunk_split(base64_encode( $anexo )); // codifica o anexo em base 64
fclose( $fp ); // fecha o arquivo

Defining the header (There are other important header information you can add to prevent email from falling into the SPAM box.)

// cabeçalho do email
$headers = "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=" . $boundary . PHP_EOL;
$headers .= "$boundary" . PHP_EOL;

HTML message definition

$mensagem  = "--$boundary" . PHP_EOL;
$mensagem .= "Content-Type: text/html; charset='utf-8'" . PHP_EOL;
$mensagem .= "Mensagem"; // Adicione aqui sua mensagem
$mensagem .= "--$boundary" . PHP_EOL;

Attaching a file

$mensagem .= "Content-Type: ". $fileType ."; name=\"". $fileName . "\"" . PHP_EOL;
$mensagem .= "Content-Transfer-Encoding: base64" . PHP_EOL;
$mensagem .= "Content-Disposition: attachment; filename=\"". $fileName . "\"" . PHP_EOL;
$mensagem .= "$anexo" . PHP_EOL;
$mensagem .= "--$boundary" . PHP_EOL;

Sending Email

mail($para, $assunto, $mensagem, $headers);

Using PHPMailer

Download PHPMailer and extract the files in the folder of your project.

Include the PHPMailer main file

require_once('caminho/para/o/phpmailer/class.phpmailer.php');

Preparing email

$email = new PHPMailer();
$email->From      = '[email protected]';
$email->FromName  = 'Seu nome';
$email->Subject   = 'Assunto';
$email->Body      = 'Corpo do email';
$email->AddAddress( '[email protected]' );

Attaching the file

$file_to_attach = 'caminho/do/arquivo/para/anexo';
$email->AddAttachment( $file_to_attach , 'nome_do_arquivo.pdf' );

Sending Email

$email->Send();

PHPMailer reduces several lines of code to a simple command $email->AddAttachment(); , much simpler! Using pure PHP will be several more lines and you will probably encounter various difficulties and bugs.

    
02.04.2014 / 17:01