Sending email via Phpmailer to Gmail

Asked

Viewed 31,386 times

13

I can’t at all send an email to my Gmail account via PHP. I had a previous project where I tried to use phpmailer and I can’t get it to work properly (2 months trying). Now I finished a website and just put it on the air, and the phpmailer doesn’t work.

Follow my HTML code:

<form class="coluna coluna-3" method="POST" action="email.php">
    Nome:<br/>
    <input type="text" name="nome" maxlength="50"/><br/>
    e-mail:<br/>
    <input type="text" name="email" maxlength="50"/><br/>
    Assunto:<br/>
    <input type="text" name="assunto" maxlength="50"/><br/>
    Mensagem:<br/>
    <textarea name="mensagem" rows="10" cols="50" maxlength="500"></textarea>
    <br/>
    <input type="submit" value="Enviar"/>
</form>

And this is the code from my file email.php:

// Inclui o arquivo class.phpmailer.php localizado na pasta phpmailer
require_once('../phpmailer/class.phpmailer.php');//já tentei sem ../ também
// Inicia a classe PHPMailer
$mail = new PHPMailer();
// Define os dados do servidor e tipo de conexão
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
$mail->IsSMTP(true); // Define que a mensagem será SMTP
$mail->Host = "smtp.gmail.com"; // Endereço do servidor SMTP
$mail->Port = 587;
$mail->SMTPAuth = true; // Usa autenticação SMTP? (opcional)
$mail->SMTPSecure = 'ssl';
$mail->Username = '[email protected]'; // Usuário do servidor SMTP
$mail->Password = 'minhasenha'; // Senha do servidor SMTP
// Define o remetente
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
$mail->From = "[email protected]"; // Seu e-mail
$mail->FromName = "Joãozinho"; // Seu nome
// Define os destinatário(s)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
$mail->AddAddress('[email protected]', 'Fulano da Silva');
// Define os dados técnicos da Mensagem
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
$mail->IsHTML(true); // Define que o e-mail será enviado como HTML
// Define a mensagem (Texto e Assunto)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
$mail->Subject  = "Mensagem Teste"; // Assunto da mensagem
$mail->Body = "Este é o corpo da mensagem de teste, em <b>HTML</b>!  :)";
$mail->AltBody = "Este é o corpo da mensagem de teste, em Texto Plano! \r\n :)";
// Define os anexos (opcional)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//$mail->AddAttachment("c:/temp/documento.pdf", "novo_nome.pdf");  // Insere um anexo
// Envia o e-mail
$enviado = $mail->Send();
// Limpa os destinatários e os anexos
$mail->ClearAllRecipients();
$mail->ClearAttachments();
// Exibe uma mensagem de resultado
if ($enviado) {
  echo "E-mail enviado com sucesso!";
}
else {
  echo "Não foi possível enviar o e-mail.";
  echo "<b>Informações do erro:</b> " . $mail->ErrorInfo;
}

It’s unnecessary to add CSS code because it won’t help at all.

I’m sending an email to myself because I’m just testing if it works. When it works, I put the texts through $_POST properly.

I’m in localhost, use Ubuntu-MATE 15.04, my server is the Apache2. The site is in /var/www/meuprojeto/ inside the briefcase meuproject, is a folder phpmailer with two files downloaded from Github - "class.phpmailer.php" and "class.smtp.php"
(follow this tutorial: Send emails via PHP using phpmailer).

To find out information from Gmail, I looked at: Send emails via PHP and SMTP using Gmail or Google Apps .

Any additional information required, just ask.

  • Could detail the mistake you receive?

  • Error: 2015-10-01 02:59:23 SMTP ERROR: Failed to connect to server: (0) 2015-10-01 02:59:23 SMTP connect() failed. github.com/Phpmailer/Phpmailer/wiki/Troubleshooting Could not send e-mail.Error information: SMTP connect() failed. github.com/Phpmailer/Phpmailer/wiki/Troubleshooting

  • php version: PHP 5.6.4-4ubuntu6.2 (cli) (built: Jul 2 2015 15:29:28) Copyright (c) 1997-2014 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies with Zend Opcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies

  • The port that Gmail uses for SSL is 465. The 587 is for TLS

  • A hint to "decrease" the security of Gmail is to touch here: https://www.google.com/settings/security/lesssecureapps You "decrease" the security of Gmail authentication to be able to release the service! Although I’m trying and still can’t make it work! So it is important to create a unique email for this task for example: [email protected] or [email protected] or something like that!

  • My solution was a mix of two responses ai: 1- In Google settings enable sending by less secure Apps; 2- Use Ssl with this port 465; 3- I did not have to release any port, I believe it was already released.

  • NOTE: posts in general that speak of "less secure applications" are outdated. It has been a long time since Phpmailer supports XOAUTH2 authentication, that allows you to use google mail normally without needing to download security, via app token.

Show 2 more comments

4 answers

5


Without any error information it is very difficult to treat the problem. Suppose you are using version 5 of Phpmailer.

Include in your file the call from autoload :

require('phpmailer/PHPMailerAutoload.php');

Activate the debug:

// 1 = Erros e mensagens
// 2 = Apenas mensagens
$mail->SMTPDebug  = 1; 

Make sure your credentials are correct;

  • I followed your suggestion with value 1 and I got the following message: 2015-10-01 02:59:23 SMTP ERROR: Failed to connect to server: (0) 2015-10-01 02:59:23 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Could not send e-mail: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

  • Are you sure your credentials are correct? You’re doing this on localhost?

  • How do I see the credentials? I’m doing it on localhost. It worked for Earth’s email, but Gmail is not going.

  • Credentials are the data email and password that you use.

  • then they are correct. I ended up choosing to use the php mail() function, the site is in the air and the email is working well. Is it some port problem that Phpmailer isn’t going to when it’s online? (on localhost it went to the ground server, but on the server it’s not)

  • 1

    I had a problem recently with a server, where it did not make any SMTP connection on it, but on the localhost I could with the same script. Check.

  • Pow, Marcelo, you said a deal that makes a lot of sense to me, because it was the server team even though they said "don’t use Phpmailer no, use the same native mail() function". I lose a lot in stopping using Phpmailer?

  • 1

    Not exactly, @Enriquerené, will depend a lot on what you need. On this matter of Soen There is a response to the use of the native mail() function and Phpmailer.

Show 3 more comments

2

You need to sign in to your Gmail account and

[enable sending by less secure Apps]

or you won’t send.

Also, please change :

De: $mail->SMTPSecure = 'ssl';

Para: $mail->SMTPSecure = '**tls**';

Now send.

0

Just to complement this post, there is another solution to email gmail from the php backend. It was the only solution that worked for me.

Just download, use the Swiftmailer and the code below. In addition, you need to change a setting in Gmail to allow access to less secure devices (google my Account -> Sign-in & security -> Conected apps & websites -> Allow Less Secure apps: ON). Due to this setting, I believe it is not a definitive solution to send emails to Gmail, but as in my case I am only using to do some tests, no problem.

Original post with this solution: https://stackoverflow.com/questions/712392/send-email-using-the-gmail-smtp-server-from-a-php-page

<?php
require_once 'swift/lib/swift_required.php';

$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
  ->setUsername('GMAIL_USERNAME')
  ->setPassword('GMAIL_PASSWORD');

$mailer = Swift_Mailer::newInstance($transport);

$message = Swift_Message::newInstance('Test Subject')
  ->setFrom(array('[email protected]' => 'ABC'))
  ->setTo(array('[email protected]'))
  ->setBody('This is a test mail.');

$result = $mailer->send($message);
?>

0

In the require_once just put the /phpmailer/class.phpmailer.php. Since it’s at the root of the project, it might work, or just phpmailer/class.phpmailer.php.

  • I used Marcelo de Andrade’s suggestion. Then (leaving his suggestion) I followed your suggestion and put only "phpmailer/class.phpmailer.php" and then appeared the error message (which I will comment on in his reply). Your tip worked, thanks for trying to help and thanks for solving in part too.

Browser other questions tagged

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