2015-04-02 183 views
0

我正在使用代碼來查找遲到的個人並向他們發送電子郵件。我也找到那些根本沒有來過的人,也給他們發郵件。但是,它不起作用。我正確地獲取了名稱和電子郵件,但$ mail對象爲空,我不明白爲什麼。

這是我的代碼:

mail_sender.php(這就是我所說的發送消息)

<?php 

function custom_mail($name, $surname, $email, $message, $subject){ 
    //$mail->SMTPDebug = 3;        // Enable verbose debug output 
     require './PHPMailer-master/PHPMailerAutoload.php'; 
     $mail = new PHPMailer(); 
     global $mail; 
     var_dump($mail); 
     $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 = '****';     // SMTP username 
     $mail->Password = '****';       // SMTP password 

     $mail->SMTPSecure = 'tls';       // Enable TLS encryption, `ssl` also accepted 
     $mail->Port = ****;         // TCP port to connect to   
     $mail->From = '****'; 
     $mail->FromName = '****'; 

     $mail->addAddress($email, $name." ".$surname);  // Add a recipient 
     $mail->addCC('****'); 
     $mail->isHTML(true);         // Set email format to HTML 
     $mail->Subject = $subject; 
     $mail->Body = ucwords($name).' '.ucwords($surname).'! <br />'.$message; 
     $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; 
     // 
     if(!$mail->send()) { 
       echo 'email -> '.$email.' name -> '.$name.' surname -> '.$surname.'<br />'; 
       echo 'Mailer Error: ' . $mail->ErrorInfo; 
     } 
     else {       
        $mail->ClearAllRecipients();  //clears the list of recipients to avoid other people from getting this email    
     } 
} 

?> 
+0

有您在您的'mail_sender.php' – 2015-04-02 09:53:24

+0

頁面'phpmailer'類是我已經列入它。但是我在錯誤的地方打電話。我現在剛剛發現了這個錯誤。感謝您的快速回復,雖然 – 2015-04-02 09:55:57

回答

1

我想這可能是你的問題:

$mail = new PHPMailer(); 
global $mail; 
var_dump($mail); 

這只是看起來不是一個好主意 - 如果您已經有一個全局定義的名爲$mail的變量,它可能會覆蓋您的PHPMailer實例,使其成爲null 。順序改成這樣:

global $mail; 
$mail = new PHPMailer(); 
var_dump($mail); 

我沒有看到有太多的理由使這個全球可用在所有 - 如果你想重新使用多次調用該實例,這不會幫助 - 你應該靜態地宣佈它要做到這一點,就像這樣:

static $mail; 
if (!isset($mail)) { 
    $mail = new PHPMailer(); 
} 
var_dump($mail); 
+0

嘗試vardump()$郵件變量,並看到這確實是問題。通常第二個聲明使其爲空。自從我嘗試了很多代碼之後,我沒有注意到我做過這些事情。另外,關於靜態聲明的好處,我會牢記這一點 – 2015-04-09 10:24:41