为什么我不能使用PHPMailer发送电子邮件?

时间:2016-04-01 03:20:11

标签: php phpmailer

这是我的代码。我真的需要知道我的代码有什么问题。我收到这个错误: - “SMTP connect()失败。https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

<?php
require_once 'PHPMailer/class.phpmailer.php';
    //sending mail for verification
    $mail = new PHPMailer();

$mail->IsSMTP(); 
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true; 
$mail->Port = 587;
$mail->Host = 'mail.mydomain.com';
$mail->Username = 'myusername'; // Enter your SMTP username
$mail->Password = "mypassword"; // SMTP password


$mail->From = "support@mydomain.com";
$mail->FromName = " Verification";
$mail->AddAddress("emailid@yahoo.com", "Name");

$mail->AddReplyTo("myemail@gmail.com", "Information");




$mail->IsHTML(true);                                  

$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 "Mail sent";
}else{
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>

我的凭据是正确的。我确实按照错误消息中的链接尝试了几乎所有提到的内容,但似乎没有什么对我有用。这是我原始代码的最短和修剪版本,我的想法是告诉我即使这对我不起作用。

1 个答案:

答案 0 :(得分:-1)

我找到解决方案我的这个问题。以下是我所做的更改,它完美无缺。

<?php
require_once 'PHPMailer/class.phpmailer.php';
require_once 'assets/import/PHPMailer/class.smtp.php'; //I added this here which wasn't added in original script
    //sending mail for verification
    $mail = new PHPMailer();

$mail->IsSMTP(); 
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true; 
$mail->Port = 587;
$mail->Host = 'mail.mydomain.com';
$mail->Username = 'myusername'; // Enter your SMTP username
$mail->Password = "mypassword"; // SMTP password


$mail->From = "support@mydomain.com";
$mail->FromName = " Verification";
$mail->AddAddress("emailid@yahoo.com", "Name");

$mail->AddReplyTo("myemail@gmail.com", "Information");

// Adding SMTPOption is the main thing that solved my problem. I got this from troubleshooting page of PHPMailer. And they
// recommended to do this only if every other option fails. 

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);


$mail->IsHTML(true);                                  

$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 "Mail sent";
}else{
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
?>