PHPMailer con account gmail

  • Creatore Discussione Creatore Discussione Dex01
  • Data di inizio Data di inizio

Dex01

Nuovo Utente
12 Gen 2018
15
0
1
26
Sto provando un software in locale con XAMPP e non avendo un server smtp da usare per testare il codice o ripiegato sull'uso di un account gmail, con questo codice (puramente di prova)

PHP:
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load Composer's autoloader
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 3;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'nome.cognome@gmail.com';                     // SMTP username
    $mail->Password   = 'password';                               // SMTP password
    //$mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 25;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('nome.cognome@gmail.com', 'Mailer');
    $mail->addAddress('nome.cognome@gmail.net', 'Joe User');     // Add a recipient
    //$mail->addAddress('ellen@example.com');               // Name is optional
    //$mail->addReplyTo('info@example.com', 'Information');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    // Attachments
    //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $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';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>

Ma il risultato è il seguente

2019-04-25 08:38:36 Connection: opening to smtp.gmail.com:25, timeout=300, options=array()
2019-04-25 08:38:36 Connection: opened
2019-04-25 08:38:37 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP z13sm15373160wrh.41 - gsmtp
2019-04-25 08:38:37 CLIENT -> SERVER: EHLO localhost
2019-04-25 08:38:37 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [79.30.129.31]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2019-04-25 08:38:37 CLIENT -> SERVER: STARTTLS
2019-04-25 08:38:37 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2019-04-25 08:38:37 Connection failed. Error #2: failed loading cafile stream: `D:\XAMP\apache\bin\curl-ca-bundle.crt' [D:\XAMP\htdocs\dashboard\HSM\class\PHPMailer\src\SMTP.php line 403]
SMTP Error: Could not connect to SMTP host.
2019-04-25 08:38:37 CLIENT -> SERVER: QUIT
2019-04-25 08:38:37 SERVER -> CLIENT: F
2019-04-25 08:38:37 SMTP ERROR: QUIT command failed: F
2019-04-25 08:38:37 Connection: closed
SMTP Error: Could not connect to SMTP host.
Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host.
 
con questi parametri utilizzo il servizio gmail
PHP:
"Host"     => "smtp.gmail.com"
"Port"     => 465
"Auth"     => true
"Secure"   => "ssl"
"username" => "CAMBIAMI@gmail.com"
"password" => "CAMBIAMI"

se poi vuoi un esempio funzionante, lo trovi qui
https://forum.mrw.it/threads/linvio...o-offerto-da-vari-provider.40100/#post-158302
Ho provato a modificare i parametri ma l'errore persiste

2019-04-26 11:25:33 Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array()
2019-04-26 11:25:33 Connection failed. Error #2: failed loading cafile stream: `D:\XAMP\apache\bin\curl-ca-bundle.crt' [D:\XAMP\htdocs\dashboard\HSM\class\PHPMailer\src\SMTP.php line 321]
2019-04-26 11:25:33 Connection failed. Error #2: stream_socket_client(): Failed to enable crypto [D:\XAMP\htdocs\dashboard\HSM\class\PHPMailer\src\SMTP.php line 321]
2019-04-26 11:25:33 Connection failed. Error #2: stream_socket_client(): unable to connect to ssl://smtp.gmail.com:465 (Unknown error) [D:\XAMP\htdocs\dashboard\HSM\class\PHPMailer\src\SMTP.php line 321]
2019-04-26 11:25:33 SMTP ERROR: Failed to connect to server: (0)
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
 
con la versione 6.0.3 di Phpmailer, ho questo codice
PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\Exception;

require_once 'PHPMailer/Exception.php';
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
require_once 'PHPMailer/OAuth.php';

differente rispetto al tuo codice
 
con la versione 6.0.3 di Phpmailer, ho questo codice
PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\Exception;

require_once 'PHPMailer/Exception.php';
require_once 'PHPMailer/PHPMailer.php';
require_once 'PHPMailer/SMTP.php';
require_once 'PHPMailer/OAuth.php';

differente rispetto al tuo codice
Ho provato a modificare l'inizio mettendo importando i file come te
PHP:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\Exception;

require_once 'src/Exception.php';
require_once 'src/PHPMailer.php';
require_once 'src/SMTP.php';
require_once 'src/OAuth.php';

Ora il codice completo sarebbe cosi (eccetto per l'ovvio censura su email e password)

PHP:
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\Exception;

require_once 'src/Exception.php';
require_once 'src/PHPMailer.php';
require_once 'src/SMTP.php';
require_once 'src/OAuth.php';
// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 3;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.gmail.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'mia_email@gmail.com';                     // SMTP username
    $mail->Password   = 'mia_passowrd';                               // SMTP password
    $mail->SMTPSecure = 'ssl';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 465;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('mia_email@gmail.com', 'Mailer');
    $mail->addAddress('mia_email@gmail.com', 'Joe User');     // Add a recipient
    //$mail->addAddress('ellen@example.com');               // Name is optional
    //$mail->addReplyTo('info@example.com', 'Information');
    //$mail->addCC('cc@example.com');
    //$mail->addBCC('bcc@example.com');

    // Attachments
    //$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $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';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

?>
E il risultato è il seguente:

2019-04-26 13:03:06 Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array()
2019-04-26 13:03:06 Connection failed. Error #2: failed loading cafile stream: `D:\XAMP\apache\bin\curl-ca-bundle.crt' [D:\XAMP\htdocs\dashboard\HSM\class\PHPMailer\src\SMTP.php line 321]
2019-04-26 13:03:06 Connection failed. Error #2: stream_socket_client(): Failed to enable crypto [D:\XAMP\htdocs\dashboard\HSM\class\PHPMailer\src\SMTP.php line 321]
2019-04-26 13:03:06 Connection failed. Error #2: stream_socket_client(): unable to connect to ssl://smtp.gmail.com:465 (Unknown error) [D:\XAMP\htdocs\dashboard\HSM\class\PHPMailer\src\SMTP.php line 321]
2019-04-26 13:03:06 SMTP ERROR: Failed to connect to server: (0)
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

Non so da cosa possa essere dovuto però
 
stiamo praticamente usando lo stesso script, in ogni caso,
ho usato il tuo script, ho modificato,
"require_once" mettendo il percorso
$mail->Username
$mail->Password
$mail->setFrom
$mail->addAddress

RISULTATO POSITIVO
upload_2019-4-26_22-32-1.png


controlla bene "require_once", secondo me sbagli il percorso,
se Phpmailer si trova nella cartella "includes" di PHP,
devi indicare l'intero percorso da questa cartella (esclusa) fino alla cartella che contiene gli script ("src")
 
stiamo praticamente usando lo stesso script, in ogni caso,
ho usato il tuo script, ho modificato,
"require_once" mettendo il percorso
$mail->Username
$mail->Password
$mail->setFrom
$mail->addAddress

RISULTATO POSITIVO
Vedi l'allegato 6324

controlla bene "require_once", secondo me sbagli il percorso,
se Phpmailer si trova nella cartella "includes" di PHP,
devi indicare l'intero percorso da questa cartella (esclusa) fino alla cartella che contiene gli script ("src")

Non può essere un probelma di require dato che se ci fosse un percorso sbagliato require al contrario di include darebbe come risultato un fatal error.

Detto ciò io nella folder alla fine ho solo la folder base di PHPMailer (dove all'interno c'è il file di prova solo per questione di testing) e le due sub folder src e lenguage quindi direi che il porcorso è proprio impossibile che sia sbagliato, se cosi fosse non la pagina si interromperebbe subito
 
su gmail devi disattivare il controllo di applicazione non desiderate .. io lo avevo fatto anni fa.. e ora funziona senza problemi. caso mai ti posto il mio contact.php. Vedi:
http://dpaste.com/3N6Z5K1

utilizza la versione con composer .

composer require phpmailer/phpmailer

ed dopo includi il file:
require 'vendor/autoload.php';

e a me funziona cosi .

ciao.
 
su gmail devi disattivare il controllo di applicazione non desiderate .. io lo avevo fatto anni fa.. e ora funziona senza problemi. caso mai ti posto il mio contact.php. Vedi:
http://dpaste.com/3N6Z5K1

utilizza la versione con composer .

composer require phpmailer/phpmailer

ed dopo includi il file:
require 'vendor/autoload.php';

e a me funziona cosi .

ciao.
Proverò adesso, comunque io non ho capito che versione è perchè dal repo di github non c'è questo vendor. Come dovrei fare ad utilizzare la versione con composer?
 
qual'è xampp usi ? .. poi ti faccio sapere con la versione che usi.. io uso la versione zipatta da sourceforge non da quella che si trova nel sito principale.. perché dal sito principale non c'è la versione non installabile. dimmi che versioni usi e ti faccio sapere come configurare anche sendmail di c:\xampp\sendmail\ e il php.ini.
 
qual'è xampp usi ? .. poi ti faccio sapere con la versione che usi.. io uso la versione zipatta da sourceforge non da quella che si trova nel sito principale.. perché dal sito principale non c'è la versione non installabile. dimmi che versioni usi e ti faccio sapere come configurare anche sendmail di c:\xampp\sendmail\ e il php.ini.
Attualmente sono con la v3.2.3, ti ringrazio ma sono obbligato ad utilizzare phpmailer al posto della semplice funzione mail
 
no. quella è la versione del panel control. Io dico il file dove hai installato .. ovvero il mio è cosi: xampp-windows-x64-7.2.17-0-VC15. più tardi ti dico come fare.. ora devo andare via.
 
prova cosi:
1 -
scaricare certificato per windows / linux qui. ..... curl.haxx.se/docs/caextract.html
--> cacert-2019-01-23.pem e copiarlo in ./ssl
2 - modificare il php.ini in queste righe:
;Curl.cainfo = "C: \ xampp \ apache \ bin \ curl-ca-bundle.crt"
Curl.cainfo = "C: \ xampp \ php \ extras \ ssl \ cacert.pem"
----
;Openssl.cafile = "C: \ xampp \ apache \ bin \ curl-ca-bundle.crt"
Openssl.cafile = "C: \ xampp \ php \ extras \ ssl \ cacert.pem"
3 -
PHP:
......
$mail = new PHPMailer(true);

            $base_url = "http://localhost/tua cartella/";  //change this baseurl value as per your file path
            $mail_body = "
            <p>Hi ".$_POST['user_name'].",</p>
            <p>Thanks for Registration. Your password is ".$user_password.", This password will work only after your email verification.</p>
            <p>Please Open this link to verified your email address - ".$base_url."email_verification.php?activation_code=".$user_activation_code."
            <p>Best Regards,<br />xxxx</p>
            ";
try {
                //Server settings
                $mail->SMTPOptions = array ('ssl'=>array ('verify_peer'=>false,'verify_peer_name'=>false,'allow_self_signed'=>true));
                $mail->SMTPDebug = 1;                                       // Enable verbose debug output
                $mail->isSMTP();                                            // Set mailer to use SMTP
                $mail->Host       = 'smtp.gmail.com';                       // Specify main and backup SMTP servers
                $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
                $mail->Username   = 'xxxxx@gmail.com';                      // SMTP username
                $mail->Password   = 'xxxxxxxxxx';                          // SMTP password
                $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
                $mail->Port       = 587;                                    // TCP port to connect to
                //Recipients
                $mail->setFrom('info@tuosito.it', 'pippo');
                $mail->addAddress('xxxxx@gmail.com');                  // Add a recipient
                //$mail->addAddress('ellen@example.com');                   // Name is optional
                //$mail->addReplyTo('info@example.com', 'Information');
                //$mail->addCC('cc@example.com');
                //$mail->addBCC('bcc@example.com');

                // Attachments
                // $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
                // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

                // To load the French version
                //$mail->setLanguage('fr', '/optional/path/to/language/directory/');
                $mail->setLanguage('it');

                //$body = '<p><strong>Hello</strong> this is my first email from PHPMailer</p>';

                // Content
                $mail->isHTML(true);                                  // Set email format to HTML
                $mail->Subject = 'Here is test email';
                $mail->Body    = $mail_body;
                $mail->AltBody = strip_tags($mail_body);

                $mail->send();
                echo 'Message has been sent';
            } catch (Exception $e) {
                echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
            }        }
    }
}
 

Discussioni simili