2015-04-02 188 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