Sending mail via PHPmailer to Gmail [closed]

13

I can not send an email to my Gmail account via PHP. I had a previous project where I tried to use phpmailer and I can not get it working properly (2 months trying). I have now finished a site and just need to put it up, and phpmailer does not work.

Here is 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 for 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 is unnecessary to add the CSS code because it will not 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 by $_POST as it should be.

I am in localhost , use ubuntu-MATE 15.04 , my server is Apache2 . The site is in /var/www/meuprojeto/ within the myproject folder, there is a phpmailer folder with two files downloaded from GitHub - " class.phpmailer.php " and " class.smtp.php "
(I followed this tutorial: Send emails using PHP using phpmailer ).

To discover Gmail information, I looked in: Send emails via PHP and SMTP using GMail or Google Apps .

Any additional information required, just ask.

    
asked by anonymous 29.09.2015 / 17:50

4 answers

5

Without any error information it is very difficult to deal with the problem. Let's say you're using version 5 of PHPMailer .

Include in your file the autoload call:

require('phpmailer/PHPMailerAutoload.php');

Enable debug:

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

Verify that the credentials are correct;

    
30.09.2015 / 21:09
1

You need to sign in to Gmail and

  

[enable less secure Apps submission]

Otherwise it will not send.

In addition, change:

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

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

Now send it.

    
04.10.2017 / 15:21
0

No require_once put only /phpmailer/class.phpmailer.php . As it is at the root of the project, it may work, or just phpmailer/class.phpmailer.php .

    
29.09.2015 / 18:59
0

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

Just download, use SwiftMailer and the code below. In addition, you need to change a setting in Gmail to allow less secure devices (google my account - > sign-in & security - > Connected apps & sites - > Allow less secure apps: ON). Due to this configuration, 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:

<?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);
?>
    
24.11.2016 / 23:00