Send email with attachments in php
I'm sending an email, it works fine. Now I wanted to add some files as 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 to it?
1 answers
Using the function mail()
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 define a boundary
for our email. The rules for generating a boundary
can be found on the internet easily. But simply put, 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 from the file that will 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
Setting the header (there is other important header information you can add to prevent the 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 your project folder.
Include the main PHPMailer 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 $email->AddAttachment();
command, much simpler! Using pure PHP will be several lines more and will probably encounter various difficulties and bugs.