E-mail with PHP attachments

Asked

Viewed 21,808 times

11

I am 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?

  • 3

    I think it’s best you use Phpmailer or another library to send emails with attachment because it’s simpler than using the mail function().

  • This might help http://wiki.locaweb.com.br/pt-br/Enviando_e-mails_com_anexo_em_PHP

1 answer

20


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 pattern the term used to identify the separator of these parts is boundary. So let’s define a boundary to our email. The rules for generating a boundary can be found in the internet easily. But simply put, it’s nothing more than a random string that should appear in the email only when indicating a part of the email.

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

Get the information from the file you 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 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;

Definition of the HTML message

$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 the email

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

Using the Phpmailer

Download the Phpmailer and extract the files in your project folder.

Include the main Phpmailer archive

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

Preparing the 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 the 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 probably will encounter several difficulties and bugs.

  • Using the mail() function, when I want to send the file, it does not come from any form. I’m fetching the file name from the BD and there may be a possibility to send more than one file as an attachment. How can I get around this issue?

  • Or even using Phpmailer, how can I add several attachments to it? Thank you

  • 2

    To send multiple files just get an array of file paths and perform a loop by executing the file attachment snippets for each path. To get the file path via BD just use what I say to get local file information. If you are like BLOB recommend saving the shipping information such as name, size and type next to the record.

  • I did it the way mail(), but only the attachment, the content of the message itself is not sent what may be occurring? @marcusagm

  • The second limit is concatenated with the top line. That’s why it doesn’t require HTML. Just insert this one in place of the second: **$message .= " n-$Boundary" . PHP_EOL; ** Just insert " n" to break a line and show both HTML and attachment

Browser other questions tagged

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