2012-01-10 6 views
31

Soy nuevo en PHP y estoy usando la función de correo para enviar correos electrónicos que no están funcionando. Me sale un mensaje de éxito, pero aún no funcionaEl correo de PHP no funciona por alguna razón

mismo código

<?php 
    $email_to = "[email protected]"; 
    $email_subject = "Test mail"; 
    $email_body = "Hello! This is a simple email message."; 


    if(mail($email_to, $email_subject, $email_body)){ 
     echo "The email($email_subject) was successfully sent."; 
    } else { 
     echo "The email($email_subject) was NOT sent."; 
    } 
?> 

Me estoy perdiendo algo, qué necesito para incluir todos los archivos para esta función .. Soy de asp.net & este es el script básico que se encuentra en el sitio web.

me trataron otras secuencias de comandos relacionados con un correo electrónico que no funcionan bien ..

Me postulo este script en el sitio web no en el host local

+0

verifique su configuración –

+0

¿Dónde se utiliza ese? En la máquina local o en un servidor? – zozo

+0

Qué configuración – Learning

Respuesta

9

Esto es probablemente un error de configuración. Si insiste en usar la función PHP mail, tendrá que editar php.ini.

Si está buscando una opción más fácil y más versátil (en mi opinión), debe usar PHPMailer.

1

Compruebe su configuración de SMTP en su archivo php.ini. Su anfitrión debe tener cierta documentación sobre qué credenciales usar. Tal vez pueda verificar su archivo de registro de errores, podría tener más información disponible.

2

La función de correo no garantiza la entrega real del correo. Todo lo que hace es pasar el mensaje al programa externo (generalmente sendmail). Necesita un servidor SMTP configurado correctamente para que esto funcione. También tenga en cuenta que no es compatible con la autenticación SMTP. Puede consultar la biblioteca PEAR :: Mail de SwiftMailer, ambos le dan más opciones.

5

Este podría ser el problema de su configuración SMTP en su archivo php.ini.

Puesto que usted nuevo en PHP, usted puede encontrar el archivo php.ini en el directorio raíz de la carpeta de instalación de PHP y comprobar si hay SMTP = y = smtp_port y cambie el valor a

SMTP = your mail server e.g) mail.yourdomain.com 
smtp_port = 25(check your admin for original port) 

En caso de que su servidor requiere autenticación para enviar correo, use la función de correo PEAR.

59

Si está utilizando Ubuntu y que parece Sendmail no está en /usr/sbin/sendmail, instalar sendmail utiliza el terminal con este comando:

sudo apt-get install sendmail 

y luego ejecutar recargar la página PHP donde mail() está escrito. También verifica tu carpeta de spam.

+2

Solucionado para mí, gracias. Estaba atrapado en esto por horas ... una solución tan simple jajaja - Solo para agregar, estoy usando un VPS 'ovh'. Entonces, si alguien en el futuro ve esto, hola :) –

0

Para HostGator, es necesario utilizar el siguiente para sus cabeceras:

$headers = 'From: [email protected]' . " " . 
'Reply-To: [email protected]' . " " . 
'X-Mailer: PHP/' . phpversion(); 

Sólo funcionaba para mí cuando el usuario fue de host de correo electrónico, mientras que el Responder-a puede ser algo diferente, por ejemplo, De: propietario @ dominio.com, Responder a: [email protected]

http://support.hostgator.com/articles/specialized-help/technical/php-email-from-header http://support.hostgator.com/articles/specialized-help/technical/how-to-use-sendmail-with-php

0

estoy usando esto por un tiempo ahora, no se sabe si esto sigue siendo hasta la fecha con las versiones actuales de PHP. Se puede utilizar esta configuración en un solo archivo, o simplemente dividirlo en dos archivos como contact.php y index.php

contact.php | Código

<?php 
error_reporting(E_ALL^E_NOTICE); 


if(isset($_POST['submitted'])) { 


if(trim($_POST['contactName']) === '') { 
    $nameError = '<span style="margin-left:40px;">You have missed your name.</span>'; 
    $hasError = true; 
} else { 
    $name = trim($_POST['contactName']); 
} 

if(trim($_POST['topic']) === '') { 
    $topicError = '<span style="margin-left:40px;">You have missed the topic.</span>'; 
    $hasError = true; 
} else { 
    $topic = trim($_POST['topic']); 
} 

$telefon = trim($_POST['phone']); 
$company = trim($_POST['company']); 


if(trim($_POST['email']) === '') { 
    $emailError = '<span style="margin-left:40px;">You have missed your email adress.</span>'; 
    $hasError = true; 
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) { 
    $emailError = '<span style="margin-left:40px;">You have missspelled your email adress.</span>'; 
    $hasError = true; 
} else { 
    $email = trim($_POST['email']); 
} 


if(trim($_POST['comments']) === '') { 
    $commentError = '<span style="margin-left:40px;">You have missed the comment section.</span>'; 
    $hasError = true; 
} else { 
    if(function_exists('stripslashes')) { 
     $comments = utf8_encode(stripslashes(trim($_POST['comments']))); 
    } else { 
     $comments = trim($_POST['comments']); 
    } 
} 


if(!isset($hasError)) { 

    $emailTo = '[email protected]'; 
    $subject = 'Example.com - '.$name.' - '.$betreff; 
    $sendCopy = trim($_POST['sendCopy']); 
    $body = "\n\n This is an email from http://www.example.com \n\nCompany : $company\n\nName : $name \n\nEmail-Adress : $email \n\nPhone-No.. : $phone \n\nTopic : $topic\n\nMessage of the sender: $comments\n\n"; 
    $headers = "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"; 

    mail($emailTo, $subject, $body, $headers); 



    $emailSent = true; 
} 
} 
?> 

STYLESHEET

} 
.formblock{display:block;padding:5px;margin:8px; margin-left:40px;} 
.text{width:500px;height:200px;padding:5px;margin-left:40px;} 
.center{min-height:12em;display:table-cell;vertical-align:middle;} 
.failed{ margin-left:20px;font-size:18px;color:#C00;} 
.okay{margin-left:20px;font-size:18px;color:#090;} 
.alert{border:2px #fc0;padding:8px;text-transform:uppercase;font-weight:bold;} 
.error{font-size:14px;color:#C00;} 

label 
{ 
margin-left:40px; 
} 

textarea 

{ 
margin-left:40px; 
} 

index.php | Forma de código

<?php header('Content-Type: text/html;charset=UTF-8'); ?> 
<!DOCTYPE html> 
<html lang="de"> 
<head> 
<script type="text/javascript" src="js/jquery.js"></script> 
</head> 
<body> 


<form action="contact.php" method="post"> 

<?php if(isset($emailSent) && $emailSent == true) { ?> 

<span class="okay">Thank you for your interest. Your email has been send !</span> 

<br> 

<br> 

<?php } else { ?> 

<?php if(isset($hasError) || isset($captchaError)) { ?> 

<span class="failed">Email not been send. Please check the contact form.</span> 

<br> 

<br> 

<?php } ?> 

<label class="text label">Company</label> 

<br> 

<input type="text" size="30" name="company" id="company" value="<?php if(isset($_POST['company'])) echo $_POST['comnpany'];?>" class="formblock" placeholder="Your Company"> 

<label class="text label">Your Name <strong class="error">*</strong></label> 

<br> 

<?php if($nameError != '') { ?> 

<span class="error"><?php echo $nameError;?></span> 

<?php } ?> 

<input type="text" size="30" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="formblock" placeholder="Your Name"> 

<label class="text label">- Betreff - Anliegen - <strong class="error">*</strong></label> 

<br> 

<?php if($topicError != '') { ?> 

<span class="error"><?php echo $betrError;?></span> 

<?php } ?> 

<input type="text" size="30" name="topic" id="topic" value="<?php if(isset($_POST['topic'])) echo $_POST['topic'];?>" class="formblock" placeholder="Your Topic"> 

<label class="text label">Phone-No.</label> 

<br> 

<input type="text" size="30" name="phone" id="phone" value="<?php if(isset($_POST['phone'])) echo $_POST['phone'];?>" class="formblock" placeholder="12345 678910"> 

<label class="text label">Email-Adress<strong class="error">*</strong></label> 

<br> 

<?php if($emailError != '') { ?> 

<span class="error"><?php echo $emailError;?></span> 

<?php } ?> 

<input type="text" size="30" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="formblock" placeholder="[email protected]"> 

<label class="text label">Your Message<strong class="error">*</strong></label> 

<br> 

<?php if($commentError != '') { ?> 

<span class="error"><?php echo $commentError;?></span> 

<?php } ?> 

<textarea name="comments" id="commentsText" class="formblock text" placeholder="Leave your message here..."><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea> 

<button class="formblock" name="submit" type="submit">Send Email</button> 
<input type="hidden" name="submitted" id="submitted" value="true"> 
<?php } ?> 

</form> 
</body> 
</html> 

JavaScript

<script type="text/javascript"> 

<!--//--><![CDATA[//><!-- 

$(document).ready(function() { 

$('form#contact-us').submit(function() { 

$('form#contact-us .error').remove(); 
var hasError = false; 

$('.requiredField').each(function() { 

if($.trim($(this).val()) == '') { 
var labelText = $(this).prev('label').text(); 

$(this).parent().append('<br><br><span style="margin-left:20px;">You have missed '+labelText+'.</span>.'); 

$(this).addClass('inputError'); 
hasError = true; 

} else if($(this).hasClass('email')) { 

var emailReg = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/; 
if(!emailReg.test($.trim($(this).val()))) { 

var labelText = $(this).prev('label').text(); 

$(this).parent().append('<br><br><span style="margin-left:20px;">You have entered a wrong '+labelText+' adress.</span>.'); 

$(this).addClass('inputError'); 
hasError = true; 
} 
} 
}); 
if(!hasError) { 

var formInput = $(this).serialize(); 

$.post($(this).attr('action'),formInput, function(data){ 

$('form#contact-us').slideUp("fast", function() {     
$(this).before('<br><br><strong>Thank You!</strong>Your Email has been send successfuly.'); 

}); 

}); 

} 
return false; 

}); 

}); 

//-->!]]> 

</script> 
Cuestiones relacionadas