Difficulties in Sending Email using PHP

Asked

Viewed 4,384 times

3

Based on the code below, used for sending email:

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

The return is always false.

  • is using some framework?

  • am not......

  • The PHP log says something?

  • because the action of your form is like this action="@routes.Assets.at("send-mail.php")"?

  • send-mail.php is the name of your file that will perform php uploading?

  • Edith. Yes Erlon Charles!

  • Igor, do you use windows? If so, to use the function mail, you need an SMTP service installed. I recommend using Phpmailer for sending emails. Already comes with smtp support, no need to install any service. (https://github.com/PHPMailer/PHPMailer)

  • Nothing Vinicius! Only Return false;

  • Rafael, I use Mac OS.

  • Take a look at this article then: http://jasper.tandy.is/blogging/php-mail-and-osx-leopard/

  • Good morning, I wonder if any of the answers helped you, if not please comment on what you think is missing.

Show 6 more comments

3 answers

3

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

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

  • Windows

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

    • Search and edit the sendmail.ini (generally 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 the php.ini:

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

    On Mac OSX Yosemite I believe to be something like (as this response from Soen):

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

    To use Gmail just access the link https://www.google.com/settings/security/lesssecureapps and to free the access select Active where it is written Access to less secure apps.

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

Alternative

Alternatively you can use Phpmailer (access should be released as described above), 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 problems with Phpmailer read the link Phpmailer/wiki

  • I already edited my php.ini, but I was not successful. how do I use this Phpmailer?

  • I installed as per your guidelines, but now after clicking send button the request becomes endless.

  • ¡2015-06-02 15:07:22 Connection: Opening to smtp.gmail.com:587, timeout=300, options=array ( ) 2015-06-02 15:11:36 SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2015-06-02 15:11:36 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

  • Li, I stopped at Gmail, Oauth2 and "Allow Less Secure apps, because I couldn’t find the get_auth_token.php file. requesting on the link https://github.com/PHPMailer/PHPMailer/wiki/Using-Gmail-with-XOAUTH2. Other previous tests are ok

  • Fixed previous errors. Now I have SSL Loaded 2015-06-02 17:53:28 Could not execute: /usr/sbin/sendmail -t -i Message could not be sent.Mailer Error: Could not execute: /usr/sbin/sendmail -t -i

  • what script?

  • i was calling the sendmail function, but already removed. Now error returned 2015-06-02 15:07:22 Connection: Opening to smtp.gmail.com:587, timeout=300, options=array ( ) 2015-06-02 15:11:36 SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2015-06-02 15:11:36 SMTP connect() failed. github.com/Phpmailer/Phpmailer/wiki/Troubleshooting Message could not be sent.Mailer Error: SMTP connect() failed. github.com/Phpmailer/Phpmailer/wiki/Troubleshooting

Show 3 more comments

2

Whenever I need it I send with Phpmailer !

Phpmailer 2.3 : Link to the 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;
}

1

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

The problem with php’s mail function is that you have to tinker with a configuration file. I always have preferences for using libraries that use SMTP.

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

Very simply, 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

  • 1

    +1 for not using the function mail() other drawbacks is mounting certain headers (email with attachment) in hand and passing certain arguments/settings to specific email servers (postfix, qmail etc).

  • 1

    In that case, I’d really rather use a specific library. Every time you need to send an email with different settings, you have to change the sendmail.ini one..

  • 1

    @rray concatenation stinks.

Browser other questions tagged

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