terça-feira, 29 de junho de 2010

Enviando email com anexo no PHP

O CÓDIGO:


function enviaEmailAnexo($emailFrom, $titulo, $mensagem, $emailTo, $cc = '', $bcc = '', $arquivo, $pasta) {
if (!$arquivo) return false;

$urlArquivo = $pasta.$arquivo;

$fp = fopen($urlArquivo,"rb");
$anexo = fread($fp,filesize($urlArquivo));          
$anexo = base64_encode($anexo);
fclose($fp);
$anexo = chunk_split($anexo);

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

$quebra = (strpos($_ENV['SERVER_SOFTWARE'], "Microsoft") === false)?"\n":"\r\n";

$mens = "--$boundary".$quebra;
$mens .= "Content-Transfer-Encoding: 8bit".$quebra;
$mens .= "Content-Type: text/html; charset=\"ISO-8859-1\"".$quebra.$quebra; //plain
$mens .= $mensagem.$quebra;
$mens .= "--$boundary".$quebra;
$mens .= "Content-Type: ".mime_content_type2($arquivo).$quebra;
$mens .= "Content-Disposition: attachment; filename=\"".$arquivo."\"".$quebra;
$mens .= "Content-Transfer-Encoding: base64".$quebra.$quebra;
$mens .= $anexo.$quebra;
$mens .= "--$boundary--".$quebra;

$headers = "MIME-Version: 1.0".$quebra;
$headers .= "From: ".$emailFrom.$quebra;
$headers .= "Reply-To: ".$emailFrom.$quebra;
$headers .= "Return-Path: ".$emailFrom.$quebra;
$headers .= "Message-ID: <".time()." TheSystem@".$_SERVER['SERVER_NAME'].">".$quebra;
$headers .= "X-Mailer: PHP v".phpversion().$quebra;
$headers .= "Content-type: multipart/mixed; boundary=\"$boundary\"".$quebra;
$headers .= "$boundary".$quebra;

if (!mail($emailTo, $titulo, $mens, $headers)) return false;
return true;
}


O USO:


enviaEmailAnexo($emailFrom, $titulo, $mensagem, $emailTo, $cc = '', $bcc = '', $arquivo, $pasta);


hasta!

Nenhum comentário:

Postar um comentário