2016-03-16 3 views
-1

Мы создали эту контактную форму давным-давно, но у нас недавно были проблемы с нашим sendmail, теперь мне нужно изменить это, чтобы использовать SMTP и что я еще не делал этого раньше. Является ли это большой работой или просто изменением нескольких строк? Любые советы приветствуются.Изменение формы php sendmail на SMTP?

Вы можете увидеть весь наш сценарий здесь, это очень просто ...

<?php 
    if(!$_POST) exit; 

    function tommus_email_validate($email) { 
     return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+\./', $email); 
    } 

    $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $comments = $_POST['comments']; 

    if(trim($name) == '') { 
     exit('<div class="error_message">You must enter your name.</div>'); 
    } else if(trim($name) == 'Name') { 
     exit('<div class="error_message">You must enter your name.</div>'); 
    } else if(trim($email) == '') { 
     exit('<div class="error_message">Please enter a valid email address.</div>'); 
    } else if(!tommus_email_validate($email)) { 
     exit('<div class="error_message">You have entered an invalid e-mail address.</div>'); 
    } else if(trim($comments) == 'Tell us what you think!') { 
     exit('<div class="error_message">Please enter your message.</div>'); 
    } else if(trim($comments) == '') { 
     exit('<div class="error_message">Please enter your message.</div>'); 
    } else if(strpos($comments, 'href') !== false) { 
     exit('<div class="error_message">Please leave links as plain text.</div>'); 
    } else if(strpos($comments, '[url') !== false) { 
     exit('<div class="error_message">Please leave links as plain text.</div>'); 
    } if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }  

    $address = '[email protected]'; 

    $e_subject = 'You\'ve been contacted by ' . $name . '.'; 

    $e_body = "You have been contacted by $name from your contact form, their additional message is as follows." . "\r\n" . "\r\n"; 
    $e_content = "\"$comments\"" . "\r\n" . "\r\n"; 
    $e_reply = "You can contact $name via email, $email (or by phone if supplied: $phone)";  

    $msg = wordwrap($e_body . $e_content . $e_reply, 70); 

    $headers = "From: $email" . "\r\n"; 
    $headers .= "Reply-To: $email" . "\r\n"; 
    $headers .= "MIME-Version: 1.0" . "\r\n"; 
    $headers .= "Content-type: text/plain; charset=utf-8" . "\r\n"; 
    $headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n"; 

    if(mail($address, $e_subject, $msg, $headers)) { 
     echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>"; 
    } 
+0

Вы пытаетесь использовать свой собственный сервер SMTP для отправки этих писем, что является размещен на другой машине? Я использую postfix для ввода моего сообщения электронной почты и просто использую [relayhost] (http://www.postfix.org/postconf.5.html#relayhost), чтобы направить туда письмо. –

+0

У меня есть собственный SMTP-сервер, проблема заключается в изменении текущего сценария выше, чтобы использовать SMTP, а не sendmail, как сейчас. –

ответ

2

Вы можете использовать пакет для обработки электронных писем, например PHPMailer, просто используйте прилагаемые методы для создания своего сообщения вместо переменной $headers. После того, как вы загрузили PHPMailer и он где-то доступ к которой вашему сценарию, замените это:

$headers = "From: $email" . "\r\n"; 
$headers .= "Reply-To: $email" . "\r\n"; 
$headers .= "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type: text/plain; charset=utf-8" . "\r\n"; 
$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n"; 

if(mail($address, $e_subject, $msg, $headers)) { 
    echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>"; 
} 

с чем-то вроде этого:

require '/path/to/PHPMailer/PHPMailerAutoload.php'; 
$mail = new PHPMailer; 
$mail->isSMTP(); 

// SMTP server details 
$mail->Host = "mail.example.com"; 
$mail->Port = 25; 
$mail->SMTPAuth = true; 
$mail->Username = "[email protected]"; 
$mail->Password = "yourpassword"; 

// message details 
$mail->setFrom($email, $email); 
$mail->addReplyTo($email, $email); 
$mail->addAddress($address, $address); 
$mail->Subject = $e_subject; 
$mail->Body = $msg; 

// send 
if($mail->send()) { 
    echo "<fieldset><div id='success_page'><p>Thank you $name, your message has been submitted to us.</p></div></fieldset>"; 
} 
else{ 
    echo 'Mailer Error: ' . $mail->ErrorInfo; 
} 
0

Вы можете сделать различные думает:

Использовать SMTP-клиент, как PHPMAIL (https://github.com/PHPMailer/PHPMailer) или PEAR (обновлено):

<?php 
require 'PHPMailerAutoload.php';  
$mail = new PHPMailer; 

//$mail->SMTPDebug = 3;        // Enable verbose debug output 

$mail->isSMTP();          // Set mailer to use SMTP 
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers 
$mail->SMTPAuth = true;        // Enable SMTP authentication 
$mail->Username = '[email protected]';     // SMTP username 
$mail->Password = 'secret';       // SMTP password 
$mail->SMTPSecure = 'tls';       // Enable TLS encryption, `ssl` also accepted 
$mail->Port = 587;         // TCP port to connect to 

$mail->setFrom('[email protected]', 'Mailer'); 
$mail->addAddress('[email protected]', 'Joe User');  // Add a recipient 
$mail->isHTML(true);         // Set email format to HTML 

$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 'Message could not be sent.'; 
    echo 'Mailer Error: ' . $mail->ErrorInfo; 
} else { 
    echo 'Message has been sent'; 
} 

Или, если вы могли бы использовать Gmail (https://support.google.com/a/answer/176600?hl=en):

// Pear Mail Library 
require_once "Mail.php"; 

$from = '<f[email protected]>'; 
$to = '<[email protected]>'; 
$subject = 'Hi!'; 
$body = "Hi,\n\nHow are you?"; 

$headers = array(
    'From' => $from, 
    'To' => $to, 
    'Subject' => $subject 
); 

$smtp = Mail::factory('smtp', array(
     'host' => 'ssl://smtp.gmail.com', 
     'port' => '465', 
     'auth' => true, 
     'username' => '[email protected]', 
     'password' => 'passwordxxx' 
    )); 

$mail = $smtp->send($to, $headers, $body); 

if (PEAR::isError($mail)) { 
    echo('<p>' . $mail->getMessage() . '</p>'); 
} else { 
    echo('<p>Message successfully sent!</p>'); 
} 

Или попробуйте этот ответ: https://stackoverflow.com/a/20338651/6058255 «ничего не модифицируйте».

+1

Я сомневаюсь, что ваш второй пример будет работать, несмотря на то, что он оставлен на втором вопросе –

+0

Я думаю, вы правы (нет пользователя и пароля), но я хочу показать разные формы для этого (для этого ссылка). Я обновил свой ответ, чтобы быть прав. Благодаря! –