Enviar formulario desde el sitio a casilla de email - realizado en php

De Wiki Locaweb

Primero crearemos el formulario (en HTML) y completamos los campos. Para esto crearemos un archivo "email.txt" que re-nombraremos como "email.html" y le pegaremos el siguiente codigo:


<html>
<head>
<script language="javascript">
 
function checa_formulario(email){
 
<!--CHECHEA EL CAMPO DEL NOMBRE-->

if (email.nome_para.value == ""){
alert("Por Favor no deje el nombre en blanco!!!");
email.nome.focus();
return (false);
}

<!--CHECHEA EL CAMPO DEL E-MAIL DESTINATARIO-->
 
if (email.email.value == ""){
alert("No deje el campo email destinatario en blanco!!!");
email.email.focus();
return (false);
}

<!--CHECHEA EL CAMPO DEL ASUNTO-->
 
if (email.assunto.value == ""){
alert("No deje el asunto en blanco!!!");
email.assunto.focus();
return (false);
}
 
<!--CAMPOS DEL FORMULARIO-->

}
</script>
<title>Enviando e-mail con PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.email {
text-transform: lowercase;
}
.texto {
color: #0000FF
}
.style1 {color: #FF0000}
 
</style>
</head>
 
<body onLoad="document.email.nome.focus();">
<form onsubmit="return checa_formulario(this)" action="envia.php" method="post" enctype="multipart/form-data" name="email">
<h1 align="center" class="style1">Formulario de email con anexo </h1>
<table width="32%" border="0" align="center">

<!--DESTINATARIO-->

<tr>
<td><div align="right"><span class="texto">Para</span></div></td>
<td><input name="nome_para" type="text" id="nome_para"></td>
</tr>
<tr>
<td><div align="right" class="texto">Email</div></td>
<td><input name="email" type="text" class="email">
</tr>

<!--ASUNTO-->

<tr>
<td><div align="right" class="texto">Asunto</div></td>
<td><input name="assunto" type="text" id="assunto"></td>
</tr>

<!--TEXTO DEL MENSAJE-->
<tr>
<td><div align="right" class="texto">Mensaje</div></td>
<td><textarea name="mensagem" cols="50" rows="10" id="mensagem"></textarea></td>
</tr>

<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Enviar"></td>
</tr>
</table>
</form>
</body>
</html>

luego crearemos un archivo (en PHP) que enviara el mail "envia.txt" que re-nombraremos a "envia.php" y le pegamos el siguiente codigo:

<?php
/*Verifica cual es el sistema operacional y ajusta el quiebre de la liea funcional del cabezal de e-mail para Windows y Linux
Existen diferencias entre el ambiente Linux y Windows, por eso la validación abajo configura la variable $quebra_linha con el caracter correcto para cada sistema_operacional
Windows utiliza "\r\n"
Linux utiliza "\n"
*/
 
if(PHP_OS == "Linux") $quebra_linha="\r\n"; //Si es Linux
elseif (PHP_OS == "WINNT") $quebra_linha="\n"; //En caso de ser Windows
else die("Ese script no funcionará correctamente en este servidor,la constante PHP_OS no retorno el parâmetro esperado.");
 
//define los datos del remitente (debe ser um e-mail de su domínio)
$email_from = 'usuario@sudominio';
 
//tomo los datos enviados en el formulario
$nome_para = $_POST["nome_para"];
$email = $_POST["email"];
$mensagem = $_POST["mensagem"];
$assunto = $_POST["assunto"];
 
//doy formato al campo del mensaje
$mensagem = wordwrap( $mensagem, 50, "<br>", 1);
 
//valido los emails
if (!ereg("^([0-9,a-z,A-Z]+)([.,_]([0-9,a-z,A-Z]+))*[@]([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])?$", $email)){
 
echo('<center>Digite un email válido</center>');
echo('<center><a href="javascript:history.go(-1)">Voltar</center></a>');
exit;
}
 
$arquivo = isset($_FILES["arquivo"]) ? $_FILES["arquivo"] : FALSE;
 
if(file_exists($arquivo["tmp_name"]) and !empty($arquivo)){
 
$fp = fopen($_FILES["arquivo"]["tmp_name"],"rb");
$anexo = fread($fp,filesize($_FILES["arquivo"]["tmp_name"]));
$anexo = base64_encode($anexo);
fclose($fp);
 
$anexo = chunk_split($anexo);
$mensagem_cabecalho = '<P><FONT color=#3300ff size=5>Mensaje entregado!!!</FONT></P>
<P>Ese email es un test enviado en formato HTML via PHP mail();!</P>
<TABLE>
<TBODY>
<TR>
<TH bgColor=#ff6666><FONT color=#ffffff><SPAN style="BACKGROUND-COLOR: #ff0000">Locaweb</SPAN></FONT></TH>
<TR>
<TD align=middle>Keep it simple</TD></TR></TBODY></TABLE>';
 
$boundary = 'XYZ-' . date("dmYis") . '-ZYX';
$mens = '--' . $boundary . $quebra_linha;
$mens .= 'Content-Transfer-Encoding: 8bits' . $quebra_linha;
$mens .= 'Content-Type: text/html; charset="ISO-8859-1"' . $quebra_linha . $quebra_linha;
$mens .= $mensagem_cabecalho . $quebra_linha;
$mens .= $mensagem . $quebra_linha;
$mens .= '--' . $boundary . $quebra_linha;
$mens .= 'Content-Type: ' . $arquivo["type"] . $quebra_linha;
$mens .= 'Content-Disposition: attachment; filename="' . $arquivo["name"] . '"' . $quebra_linha;
$mens .= 'Content-Transfer-Encoding: base64' . $quebra_linha . $quebra_linha;
$mens .= $anexo . $quebra_linha;
$mens .= '--' . $boundary . '--' . $quebra_linha;
 
$headers = 'MIME-Version: 1.0' . $quebra_linha;
$headers .= 'From: ' . $email_from . $quebra_linha;
$headers .= 'Return-Path: ' . $email_from . $quebra_linha;
$headers .= 'Content-type: multipart/mixed; boundary="' . $boundary . '"' . $quebra_linha;
$headers .= $boundary . $quebra_linha;
 
//envio el email con el anexo
mail($email,$assunto,$mens,$headers);
 
echo('Email enviado!');
}
 
//se no existe anexo
else{
 
$headers = 'MIME-Version: 1.0' . $quebra_linha;
$headers .= 'Content-type: text/html; charset=iso-8859-1' . $quebra_linha;
$headers .= 'From: ' . $email_from . $quebra_linha;
 
//envia email sin anexo
mail($email,$assunto,$mensagem, $headers);
 
echo('Email enviado!');
}
 
?>


teniendo estos dos archivos (.html y .php) debemos subirlo a nuestro servidor por ftp a la carpeta que corresponda de nuestra area de hospedaje y ejecutar la aplicaciòn en la direcciòn http://sudominio/email.html


Contenido

Dónde Comprar


Continuación del tutorial

Vea también


Links

Herramientas personales