Difficulties in sending E-mail using PHP

3

Based on the code below, used for sending e-mail:

<?php
    $from     =  $_POST['email'];
    $to       = '[email protected]';
    $subject  =  $_POST['subject'];
    $message  =  $_POST['content'];
    $headers  = 'From: ' . $from . "\r\n" .
            'MIME-Version: 1.0' . "\r\n" .
            'Content-type: text/html; charset=utf-8';
    if(mail($to, $subject, $message, $headers))
       echo "Email sent";
    else
       echo "Email sending failed";
?>

And the form:

<form action="/mail/send-mail.php" method="post">
    <div class="form-group">
        <input type="text" class="form-control" name="name" id="contact-name" placeholder="Nome">
    </div>
    <div class="form-group">
         <input type="email" class="form-control" name="email" id="contact-email" placeholder="Email">
    </div>
    <div class="form-group">
         <input type="text" class="form-control" name="subject" id="contact-subject" placeholder="Assunto">
    </div>
    <div class="form-group">
         <textarea class="form-control" name="content" id="contact-content" placeholder="Mensagem" rows="3"></textarea>
    </div>
    <button type="submit" class="btn btn-default text-uppercase" id="contactButton"> Enviar</button>
 </form>

Return is always false.

    
asked by anonymous 01.06.2015 / 21:16

3 answers

3

If the message Email sending failed always appears and the false to which you refer is the mail function, then the reason is the configuration of your server.

Note that if you are trying to use this in http://localhost and not a real server the mail function will not work and will always always return false , if you are trying to configure your own server you will need to configure SMTP in php .ini:

  • Windows

    If it is Windows you will need an application called sendmail which is usually already installed with linux (in Windows sendmail comes with the Xampp package (Wamp / zwamp / easyphp does not have such software in the package) p>

    • Search and edit sendmail.ini (usually in Xampp for windows C:\xampp\sendmail ):

      [sendmail]
      smtp_server=smtp.gmail.com
      smtp_port = 587
      default_domain = gmail.com
      
      auth_username=[seuemail]@gmail.com
      auth_password=[suasenha]
      
    • Edit php.ini :

      [mail function]
      sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
      SMTP = smtp.gmail.com
      smtp_port = 587
      
  • Mac OSX

    In Mac OSX Yosemite I think it's something like (as is the response from SOen ):

    [mail function]
    sendmail_path = "env -i /usr/sbin/sendmail -t -i"
    SMTP = smtp.gmail.com
    smtp_port = 587
    
  • Setting up Gmail

    To use Gmail, simply go to the link link and to free access select Active strong> where Access to less secure applications is written.

    For more details on Gmail follow the instructions in this link .

Alternative

Alternatively, you can use PHPMailer (you must release the access as described above), for example:

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, 'ssl' also accepted
$mail->Port = 587;                                    // TCP port to connect to

$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

For other issues with PHPMailer, read the link PHPMailer / wiki

    
01.06.2015 / 21:26
2

Whenever I need to send with PHPMailer!

PHPMailer 2.3 > Link to class

<?php

require("phpmailer/class.phpmailer.php");


$mail = new PHPMailer();

$mail->IsSMTP();
$mail->Host = "ssl://smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPDebug = 0;
$mail->Port = 465;
$mail->SMTPSecure = 'tls';
$mail->Username = '[email protected]';
$mail->Password = 'sua_senha';

$mail->From = "[email protected]";
$mail->Sender = "[email protected]";
$mail->FromName = "Nome do remetente";

$mail->AddAddress('[email protected]', 'Assunto da mensagem');

//$mail->AddCC('[email protected]', 'Aqui o nome');
//$mail->AddBCC('emailcomcopia@oculta', 'Aqui o nome');

$mail->IsHTML(true);
$mail->CharSet = 'utf-8';

$mail->Subject = "Assunto da Mensagem"; // Assunto da mensagem
$mail->Body = "Mensagem";


// Anexos
//$mail->AddAttachment("caminho/para/arquivo.pdf", "novo_nome.pdf");

$enviado = $mail->Send();

$mail->ClearAllRecipients();
$mail->ClearAttachments();

if ($enviado) {
    echo "E-mail enviado com sucesso!";
} else {
    echo "Não foi possível enviar o e-mail.";
    echo "Informações do erro:" . $mail->ErrorInfo;
}
    
04.06.2015 / 01:30
1

I use frameworks. They usually have their own mechanisms that do not use the PHP mail function.

The problem with the php mail function is that you have to tinker with a configuration file. I have always preferred to use libraries that use SMTP.

For example, this is the case of Nette\Email .

Simply put, you can send an email.

use Nette\Mail\Message;
use Nette\Mail\SmtpMailer;

$mail = new Message;
$mail->setFrom('John <[email protected]>')
    ->addTo('[email protected]')
    ->addTo('[email protected]')
    ->setSubject('Order Confirmation')
    ->setHTMLBody("<b>Hello</b>, Your order has been accepted.");


$mailer = new SmtpMailer(array(
        'host' => 'smtp.gmail.com',
        'username' => '[email protected]',
        'password' => '*****',
        'secure' => 'ssl',
));
$mailer->send($mail);

This library can be easily installed via composer.

composer require nette/mail

    
15.01.2016 / 15:43