使用phpmailer发送电子邮件

时间:2016-12-14 12:13:02

标签: php codeigniter phpmailer

我正在尝试使用PHPMailer我的控制器代码发送邮件

public function register(){ $this->form_validation->set_rules('username', 'Usename Name', 'trim|required|min_length[3]|max_length[30]');
    $this->form_validation->set_rules('email', 'Email ID', 'trim|required|valid_email|is_unique[employer_registration.email]');
    $this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|numeric');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|md5');
    if ($this->form_validation->run() == FALSE)
    {
        $this->load->view('employer/emp_register');
    }
    else
    {
        $data = array(
            'username' => $this->input->post('username'),
            'email' => $this->input->post('email'),
            'mobile' => $this->input->post('mobile'),
            'password' => $this->input->post('password')
        );
        $email = $this->input->post('email');
        $username = $this->input->post('username');
    // insert form data into database
        if ($this->Employer_model->insertUser($data))
        {
            require 'PHPMailerAutoload.php';
            require 'class.phpmailer.php';
            $mail = new PHPMailer;
            $mail->isSMTP();
            $mail->SMTPAuth = true;
    $subject = 'Testing Email';
            $username = $username;
            $email = $email;
            $body = "Thank you for register your username is $username";
            $mail->AddAddress($email);
            $mail->IsMail();
            $mail->From = 'domainname.com';
            $mail->IsHTML(true);
            $mail->Subject = $subject;
            $mail->Body  = $body;
            $mail->Send();

            if(!$mail->send())
            {
                echo "<script>alert('Sorry! mail not sent')</script>";
               echo 'Mailer Error: ' . $mail->ErrorInfo;
            }
            else
                {
                echo "<script>alert('Email sent to $email mail id')</script>";
                 }
    }}}

我已经从github下载了phpmailer文件夹,在我的项目PHPMailerAutoload文件中包含它仍然在成功注册后我无法发送邮件到注册的电子邮件ID。我收到错误,如邮件程序错误:无法实例化邮件功能。

1 个答案:

答案 0 :(得分:1)

您正在使用SMTP身份验证,但您实际上并未定义任何主机,这是必需的:

例如:$mail->Host = "smtp.example.com";

$mail->isSMTP();之后将其更改为您的域名。

另外,如果需要,您可以选择提供这样的用户名和密码:

$mail->Username = 'username'; $mail->Password = 'password';