Отправить письмо с помощью SMTP в PHP с PHPMailer - PullRequest
0 голосов
/ 26 сентября 2018

Я попробовал этот код:

<?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 '/home/username/public_html/vendor/autoload.php';



/**
     * @param type $array
     * @param type $int
     * @return type
     */
    function send_mail_customer($nickname, $email, $total_value)
    {
        $to      = $email;
        $subject = 'DISTRIBUIÇÃO DE LUCRO: ' . $nickname ;

        $from = "myname@mydomain.com";
        $name = $nickname;

        $message = "<html><body>";
        $message .= "<H1> DISTRIBUIÇÃO MENSAL DE LUCRO </H1>";
        $message .= "<strong>Total ganho:</strong> " .$total_value. " euros";
        $message .= "</body></html>";


        $mail = new PHPMailer(true);                              // Passing `true` enables exceptions
        try {
            //Server settings
            $mail->SMTPDebug = 2;                                 // Enable verbose debug output
            $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'mail.mydomain.com';                   // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = 'Myname@mydomain.com';          // SMTP username
            $mail->Password = 'Mypassword';                       // SMTP password
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 465;                                    // TCP port to connect to 587

            //Recipients
            $mail->setFrom($from, 'MyDomain');
            $mail->addAddress($to, $nickname);     // Add a recipient
            //$mail->addAddress('contact@example.com');               // Name is optional
            $mail->addReplyTo($from, 'MyDomain');
            //$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 = $subject;
            $mail->Body    = $message;
            //$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.';
            echo 'Mailer Error: ' . $mail->ErrorInfo;
        }

    }

    $x="NunoSousa";
    $email="myemail@gmail.com";
    $total_value = 15;
    send_mail_customer($x, $email, $total_value);

?>

И я получаю сообщение об ошибке:

2018-09-26 08:06:21 ОШИБКА SMTP: Не удалось подключиться к серверу: (0) SMTP соединение () не удалось.https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Сообщение не может быть отправлено. Ошибка продавца: SMTP-соединение () не удалось.https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Я читаю вики, но просто не вижу, что не так.Я пробовал также шифрование TLS с портом 587, и проблема все та же.

Ответы [ 3 ]

0 голосов
/ 26 сентября 2018

Может быть, ваш Хозяин не прав.В моем случае мой хост называется smtp.domain.com.Также я использую tls с портом 587, вы можете повторить попытку подключения с использованием правильного хоста.

В вашем случае это будет

 $mail->Host = 'smtp.mydomain.com';
 $mail->SMTPSecure = 'tls';
 $mail->Port = 587;
0 голосов
/ 26 сентября 2018

Ваш почтовый хост, установите IP-адрес вашего сервера:

$mail->SMTPDebug = 0;  // Enable verbose debug output, default is 2
$mail->isSMTP();   // Set mailer to use SMTP
$mail->Host = ''; 
$mail->SMTPAuth = true;  // Enable SMTP authentication
$mail->Username = '';    // SMTP username
$mail->Password = '';    // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also 
                          //accepted
$mail->Port = 587; 
0 голосов
/ 26 сентября 2018

Изменить

 $mail->SMTPSecure = 'ssl';  

На

 $mail->SMTPSecure = 'tls'; 
 $mail->Host = 'smtp.gmail.com'; 
 $mail->Port = 587; 
...