2015-07-16 2 views
0

У меня возникла проблема с отправкой почты с использованием phpmailer. Я начинающий программист. Я пытаюсь сделать контактную форму. Мой код выглядит следующим образом (submit.php). Пожалуйста, предложите мне .. Спасибо заранее.phpmailer - электронная почта не отправляется в gmail

session_start();  
require_once 'libs/phpmail/PHPMailerAutoload.php'; 
$errors = array(); 

if(isset($_POST['name'], $_POST['phone'],$_POST['mail'],$_POST['message'])){ 

    $fields = array(
     'name' => $_POST['name'], 
     'phone' => $_POST['phone'], 
     'email' => $_POST['mail'], 
     'message' => $_POST['message'] 
    ); 

    foreach ($fields as $field => $data) { 
     if(empty($data)){ 
      $errors[] = 'The '. $field . ' field is required'; 
     } 
    } 

    if(empty($errors)){ 

     $m = new PHPMailer; 

     $m -> isSMTP(); 
     $m -> SMTPAuth = true; 

     //$m -> SMTPDebug = 2; 

     $m -> Host = 'smtp.gmail.com'; 
     $m -> Username = '[email protected]'; 
     $m -> Password = 'xxxx'; 
     $m -> SMTPSecure = 'ssl'; 
     $m -> Port = 465; 

     $m -> isHTML(); 
     $m -> Subject = 'Contact form submitted'; 
     $m -> Body = 'From: ' . $fields['name']. '('. $fields['phone'] . $fields['email']. ')'.'<p>' .$fields['message'] .'</p> '; 

     $m -> FromName = 'Contact'; 

     // $m ->addReplyTo($fields['email'], $fields['name']); 

     $m -> addAddress('[email protected]', 'xxxxxxxx'); 

     if($m->send()){ 
      header('Location: thanks.php'); 
      die(); 


     }else{ 
      $errors[] = 'Sorry could not send email. Please try again'; 

     } 

    } 


}else{ 
    $errors[] = 'some thing went wrong'; 
} 

$_SESSION['error'] = $errors; 
$_SESSION['field'] = $fields; 


header('Location: form.php'); 
+0

Какая ошибка вы получаете? Попробуйте заменить строку 51 на $ errors [] = «Ошибка Mailer:». $ M-> ErrorInfo; – MazzCris

+0

Если вы новичок, вам нужно знать некоторые основы - во-первых, если вы собираетесь использовать библиотеку, прочитайте [документацию] (https://github.com/PHPMailer/PHPMailer/wiki) и используйте [примеры, которые приходят с ним] (https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps), поскольку они, скорее всего, будут лучше, чем те, которые вы найдете в другом месте, так как в этом случае , В этом случае [руководство по поиску и устранению неисправностей] (https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting) содержит именно то, что вам нужно знать, и вы могли бы найти его быстрее и беспокоить меньше людей, направляясь прямо туда. – Synchro

+0

Я удалил $ m -> isSMTP(); и это сработало –

ответ

0

Моя установка PHPMailer, все работает

function __construct ($to, $subject, $body) { 
      date_default_timezone_set('Etc/UTC'); 
    //Create a new PHPMailer instance 
      $mail = new PHPMailer; 
    //Tell PHPMailer to use SMTP 
      $mail->isSMTP(); 
    //Enable SMTP debugging 
    // 0 = off (for production use) 
    // 1 = client messages 
    // 2 = client and server messages 
      $mail->SMTPDebug = 0; 
    //Ask for HTML-friendly debug output 
      $mail->Debugoutput = 'html'; 
      $mail->CharSet = 'UTF-8'; 
    //Set the hostname of the mail server 
      $mail->Host = "mail.xxxxxx.com"; 
    //Set the SMTP port number - likely to be 25, 465 or 587 
      $mail->Port = 25; 
//Whether to use SMTP authentication 
     $mail->SMTPAuth = true; 
     $mail->AuthType = 'PLAIN'; 
//Username to use for SMTP authentication 
     $mail->Username = "xxxx"; 

//Password to use for SMTP authentication 
     $mail->Password = "xxxx"; 
//Set who the message is to be sent from 
     $mail->setFrom('[email protected]'); 
//Set an alternative reply-to address 
//$mail->addReplyTo('[email protected]', 'First Last'); 
//Set who the message is to be sent to 
     $mail->addAddress($to); 
//Set the subject line 
     $mail->Subject = $subject; 
//Read an HTML message body from an external file, convert referenced images to embedded, 
//convert HTML into a basic plain-text alternative body 
     $mail->msgHTML($body); 

//Replace the plain text body with one created manually 
     $mail->AltBody = 'This is a plain-text message body'; 
//Attach an image file 
//$mail->addAttachment('images/phpmailer_mini.png'); 

     $this->mail = $mail; 

    } 

    function SendMail() { 
     //send the message, check for errors 
     if (!$this->mail->send()) { 
      return "Mailer Error: " . $this->mail->ErrorInfo; 
     } else { 
      return true; 
     } 

    } 

// using 
$email = $this->request->getPost('email'); 
$smtp = new \SmtpClient($email, 'Test', $template); 
$result = $smtp->SendMail(); 
0

Удалить

$m -> Subject = 'Contact form submitted'; 

И попробуйте еще раз.

Когда я удаляю subject, он сработал.

Смежные вопросы