Как отправить автоответчик с помощью PHPMailer - PullRequest
0 голосов
/ 26 февраля 2019

Я пытаюсь создать форму запроса и отправить данные на мою электронную почту с помощью PHPMailer.Я получаю данные, которые отправляются через форму, но я не могу отправить подтверждение клиенту, который заполнил форму.Пока это моя форма:

<form class="myForm" action="" id="iForm" method="POST">
        <input type="text"  id="Name" placeholder="Name" required> 
        <input type="email" id="Email" placeholder="Email" required>
        <input type="tel"   id="Phone" placeholder="Phone Number" required>
        <input type="text"  id="Date" placeholder="Schedule a call" required>
        <textarea id="Message" rows="5" placeholder="Your Message"  required></textarea>
        <div class="form-group">
             <button type="submit" class="btn cbtn">SUBMIT</button>
        </div>
</form>

Передача данных из отправленной формы

$("#iForm").on('submit', function(e) {
e.preventDefault();
var data = {
    name: $("#Name").val(),
    email: $("#Email").val(),
    phone: $("#Phone").val(),
    date: $("#Date").val(),
    message: $("#Message").val()
};

if ( isValidEmail(data['email']) && (data['name'].length > 1) && (data['date'].length > 1) && (data['message'].length > 1) && isValidPhoneNumber(data['phone']) ) {
    $.ajax({
        type: "POST",
        url: "php/appointment.php",
        data: data,
        success: function() {
            $('.success.df').delay(500).fadeIn(1000);
            $('.failed.df').fadeOut(500);
        }
    });
} else {
    $('.failed.df').delay(500).fadeIn(1000);
    $('.success.df').fadeOut(500);
}

return false;
});

Проверка действующего адреса электронной почты

function isValidEmail(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

Проверка действительногономер телефона

function isValidPhoneNumber(phoneNumber) {
    return phoneNumber.match(/[0-9-()+]{3,20}/);
}

Это код, который я использую от PHPMailer:

$_name      = $_REQUEST['name'];
$_email     = $_REQUEST['email'];
$_phone     = $_REQUEST['phone'];
$_date      = $_REQUEST['date'];
$_message   = $_REQUEST['message'];

$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->CharSet    = 'UTF-8';
$mail->SMTPDebug  = 0;
$mail->SMTPAuth   = TRUE;
$mail->SMTPSecure = "tls";
$mail->Port       = 587;
$mail->Username   = "office@myhost.co.uk";
$mail->Password   = "********";
$mail->Host       = "myhost.co.uk";

$mail->setFrom('office@myhost.co.uk', 'Alex');
$mail->addAddress('me@gmail.com', 'Alex');

$mail->isHTML(true);
$mail->Subject     = 'New inquiry from CC';
$mail->Body        = <<<EOD
     <strong>Name:</strong> $_name <br>
     <strong>Email:</strong> <a href="mailto:$_email?subject=feedback" "email me">$_email</a> <br> <br>
     <strong>Phone:</strong> $_phone <br>
     <strong>Booking Date:</strong> $_date <br>
     <strong>Message:</strong> $_message <br>

Я пытался использовать это, делая еще один экземпляр PHPMailer и отправить письмо клиентус помощью электронной почты, которую они предоставили.

if($mail->Send()) {
$autoRespond = new PHPMailer();
$autoRespond->setFrom('office@myhost.co.uk', 'Alex');
$autoRespond->AddAddress($_email); 
$autoRespond->Subject = "Autorepsonse: We received your submission"; 
$autoRespond->Body = "We received your submission. We will contact you";

$autoRespond->Send(); 
}

Я попробовал несколько онлайн-решений для этого безуспешно.Есть идеи?

1 Ответ

0 голосов
/ 26 февраля 2019

Я наконец нашел решение своей проблемы.По сути, все вышеизложенное является правильным, единственное, что я пропустил, это снова передал параметры SMTP новому экземпляру PHPMailer.Итак, теперь последний фрагмент кода, который вызвал проблему, выглядит так:

if($mail->Send()) {
   $autoRespond = new PHPMailer();

   $autoRespond->IsSMTP();
   $autoRespond->CharSet    = 'UTF-8';
   $autoRespond->SMTPDebug  = 0;
   $autoRespond->SMTPAuth   = TRUE;
   $autoRespond->SMTPSecure = "tls";
   $autoRespond->Port       = 587;
   $autoRespond->Username   = "office@myhost.co.uk";
   $autoRespond->Password   = "********";
   $autoRespond->Host       = "myhost.co.uk";

   $autoRespond->setFrom('office@myhost.co.uk', 'Alex');
   $autoRespond->addAddress($_email);
   $autoRespond->Subject = "Autorepsonse: We received your submission"; 
   $autoRespond->Body = "We received your submission. We will contact you";

   $autoRespond->Send(); 

}

Спасибо всем за помощь.

...