Я знаю, что это частый вопрос, и я прочитал по нему сотни статей, но, будучи любителем, я не нашел идеального решения, которое ищу.
У меня есть форма на моем веб-сайте, где клиенты могут заказать услугу. Я просто хочу знать, где в приведенных ниже кодах я помещаю коды SMTP, чтобы он работал нормально.
Я использую GSuite для своей деловой электронной почты, поэтому прошу вас предоставить решение с помощью Google SMTP.
Заранее спасибо, если кто-нибудь может мне помочь.
Ваше пиво будет на мне, если решение будет таким, как я хочу.
Код HTML-формы:
<div class = "col-sm-8 col-sm-offset-2">
<form id = "test_form" action = "va_contact.php" method = "post">
<div class = "row form-group">
<div class = "col-sm-12 g1">Your Information</div>
<div class = "col-sm-4"><label class = "g2" for = "first-name-1">First Name <font color = "red">*</font></label>
<input class = "form-control" id = "first-name-1" name = "pt_first" value = "" type = "text" maxlength = "50" required></div>
<div class = "col-sm-4"><label class = "g2" for = "initial-1">Middle Initial</label>
<input class = "form-control" id = "initial-1" name = "pt_initial" value = "" type = "text" maxlength = "5"></div>
<div class = "col-sm-4"><label class = "g2" for = "last-name-1">Last Name <font color = "red">*</font></label>
<input class = "form-control" id = "last-name-1" name = "pt_last" value = "" type = "text" maxlength = "50" required></div>
<div class = "col-sm-12 g1">Address</div>
<div class = "col-sm-8"><label class = "g2" for = "street-address">Street Address <font color = "red">*</font></label>
<input class = "form-control" id = "street-address" name = "pt_address" value = "" type = "text" maxlength = "200"></div>
<div class = "col-sm-4"><label class = "g2" for = "city">City <font color = "red">*</font></label>
<input class = "form-control" id = "city" name = "pt_city" value = "" type = "text" maxlength = "50"></div>
<div class = "col-sm-4"><label class = "g2" for = "state">State/Province <font color = "red">*</font></label>
<input class = "form-control" id = "state" name = "pt_state" value = "" type = "text" maxlength = "50" required></div>
<div class = "col-sm-4"><label class = "g2" for = "zip">Zip/Postal Code <font color = "red">*</font></label>
<input class = "form-control" id = "zip" name = "pt_zip" value = "" type = "text" maxlength = "10" required></div>
<div class = "col-sm-4"><label class = "g2" for = "country">Country <font color = "red">*</font></label>
<input class = "form-control" id = "country" name = "pt_country" value = "" type = "text" maxlength = "50" required></div>
<div class = "col-sm-12 g1">Contact Details</div>
<div class = "col-sm-4"><label class = "g2" for = "phone-type">Phone Type <font color = "red">*</font></label>
<select class = "form-control" id = "phone-type" name = "pt_phone_type" required>
<option selected = "selected" value = "">Please Select One</option>
<option value = "Cell">Mobile</option>
<option value = "Home">Home / Landline</option>
<option value = "Work">Work / Office</option>
</select>
</div>
<div class = "col-sm-4"><label class = "g2" for = "phone">Preferred Phone <font color = "red">*</font></label>
<input class = "form-control" id = "phone" name = "pt_phone" value = "" type = "tel" maxlength = "25" required></div>
<div class = "col-sm-4"><label class = "g2" for = "first-name-1">Alternate Phone</label>
<input class = "form-control" id = "phone-alt" name = "pt_phone_alt" value = "" type = "tel" maxlength = "25"></div>
<div class = "col-sm-6"><label class = "g2" for = "email">Email Address <font color = "red">*</font></label>
<input class = "form-control agileits-w3layouts" id = "email" name = "email" value = "" type = "email" maxlength = "50" required></div>
<div class = "col-sm-6"><label class = "g2" for = "conf-email">Alternate Email Address</label>
<input class = "form-control" id = "conf-email" name = "alt_email" value = "" type = "email" maxlength = "50"></div>
<div class = "col-sm-12 g1">Payment Information</div>
<div class = "col-sm-4"><label class = "g2" for = "card-type">Credit Card Type <font color = "red">*</font></label>
<select class = "form-control" id = "card-type" name = "pt_card_type" required>
<option selected = "selected" value = "">Please Select One</option>
<option value = "Cell">Visa</option>
<option value = "Home">Master Card</option>
<option value = "Work">American Express</option>
<option value = "Work">Maestro Card</option>
<option value = "Work">Other</option>
</select></div>
<div class = "col-sm-4"><label class = "g2" for = "cc">Credit Card Number <font color = "red">*</font></label>
<input class = "form-control" id = "cc" name = "pt_cc" value = "" type = "text" maxlength = "20" required></div>
<div class = "col-sm-4"><label class = "g2" for = "cvv">CVV <font color = "red">*</font></label>
<input class = "form-control" id = "cvv" name = "cvv" value = "" type = "password" maxlength = "5" required></div>
<div class = "col-sm-8"><label class = "g2" for = "ccname">Name on Credit Card <font color = "red">*</font></label>
<input class = "form-control" id = "ccname" name = "ccname" value = "" type = "text" maxlength = "50" required></div>
<div class = "col-sm-4"><label class = "g2" for = "ed">Expiry Date <font color = "red">*</font></label>
<input class = "form-control" id = "ed" type = "text" name = "ed" placeholder = "MM/YYYY" maxlength = "7" required></div>
<div class = "col-sm-12 g1">Subscription Plans</div>
<div class = "col-sm-12 g2">Select the Virtual Assistant Service Plan</div>
<div class = "cc-selector col-sm-4">
<label for = "va-25" class = "drinkcard-cc va-25">
<input type = "radio" id = "va-25" name = "testRadio" required value = "va-25">
</label>
<label class = "g3" for = "first-name-1"><strong>Plan:</strong> $25 / Month</label>
</div>
<div class = "cc-selector col-sm-4">
<label for = "va-109" class = "drinkcard-cc va-109">
<input type = "radio" id = "va-109" name = "testRadio" value = "va-109">
</label>
<label class = "g3" for = "first-name-1"><strong>Plan:</strong> $109 / Month</label>
</div>
<div class = "cc-selector col-sm-4">
<label for = "va-179" class = "drinkcard-cc va-179">
<input type = "radio" id = "va-179" name = "testRadio" value = "va-179">
</label>
<label class = "g3" for = "first-name-1"><strong>Plan:</strong> $179 / Month</label>
</div>
<div class = "cc-selector col-sm-4">
<label for = "va-349" class = "drinkcard-cc va-349">
<input checked = "checked" type = "radio" id = "va-349" name = "testRadio" value = "va-349">
</label>
<label class = "g3" for = "first-name-1"><strong>Plan:</strong> $349 / Month</label>
</div>
<div class = "cc-selector col-sm-4">
<label for = "va-599" class = "drinkcard-cc va-599">
<input type = "radio" id = "va-599" name = "testRadio" value = "va-599">
</label>
<label class = "g3" for = "first-name-1"><strong>Plan:</strong> $599 / Month</label>
</div>
<div class = "cc-selector col-sm-4">
<label for = "va-999" class = "drinkcard-cc va-999">
<input type = "radio" id = "va-999" name = "testRadio" value = "va-999">
</label>
<label class = "g3" for = "first-name-1"><strong>Price:</strong> $999 / Month</label>
</div>
<div class = "form-group col-sm-12">
<label class = "g2"><font color = "#ffffff">.</font></label>
<div class = "form-group">
<font size = "2px" color = "#000000">On submit, I assured that I have read and agree with the</font>
<a href = "javascript:void(0);" onclick = "javascript:void window.open('https://www.xpertbaba.com/user-agreement','1496619568177','width=auto,height=500,toolbar=0,menubar=0,location=0,status=1,scrollbars=1,resizable=1,left=0,top=0');return false;"><font size = "2px" color = "#1880B4"> User Agreement (click here)</font></a>
</div>
</div>
<div class = "col-sm-12 text-left">
<button type = "submit" value = "Submit" class = "btn">Submit</button>
</div>
</div>
</form>
</div>Код PHP:
<?php
/* Set e-mail recipient */
$myemail = "[email protected]";
$subject = "New Sign Up";
/* Check all form inputs using check_input function */
$firstname = check_input($_POST['pt_first'], "Enter your First Name");
$lastname = check_input($_POST['pt_last'], "Enter your Last Name");
$middle_ini = check_input($_POST['pt_initial'], "Enter your Middle Name Initial");
$sadress = check_input($_POST['pt_address'], "Enter your street address");
$city = check_input($_POST['pt_city'], "Enter your city");
$state = check_input($_POST['pt_state'], "Enter your state");
$zip = check_input($_POST['pt_zip'], "Enter your zip code");
$country = check_input($_POST['pt_country'], "Enter your country");
$phone_type = check_input($_POST['pt_phone_type']);
$phone = check_input($_POST['pt_phone']);
$alt_phone = check_input($_POST['pt_phone_alt']);
$email = check_input($_POST['email']);
$alt_email = check_input($_POST['alt_email']);
$cc_type = check_input($_POST['pt_card_type']);
$cc_no = check_input($_POST['pt_cc']);
$cc_cvv = check_input($_POST['cvv']);
$cc_ed = check_input($_POST['ed']);
$cc_name = check_input($_POST['ccname']);
$va_plan = check_input($_POST['testRadio']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?://+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}
/* Let's prepare the message for the e-mail */
$message = "Hello!
Your contact form has been submitted by:
Personal Information:
First Name: $firstname
Middle Initial: $middle_ini
Last Name: $lastname
Street Address: $sadress
City: $city
State: $state
Zip Code: $zip
Country: $country
Contact Information:
Phone Type: $phone_type
Phone Number: $phone
Alternate Phone No.:
E-mail: $email
Alternate Email: $alt_email
Payment Information:
Credit Card Type: $cc_type
Credit Card Number: $cc_no
CVV Number: $cc_cvv
Credit Card Expiry Date: $cc_ed
Name on Credit Card: $cc_name
Subscription Plan: $va_plan
End of message
";
/* Send the message using mail() function */
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($myemail, $subject, $message, $headers);
/* Redirect visitor to the thank you page */
header('Location: confirmation.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>Спасибо за ваш комментарий. Но я этого не понял. Не могли бы вы сообщить мне, нужно ли для этого написать какие-либо коды в файле PHP?
Если есть какой-либо код, который вам нужно написать, это, вероятно, настройки и / или инициализация для библиотеки PHP, которую вы используете. Попробуйте заглянуть в документацию вашей почтовой библиотеки, например PHPMailer.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Замените этот код в своем php файле
/* Send the message using mail() function */
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($myemail, $subject, $message, $headers);
/* Redirect visitor to the thank you page */
header('Location: confirmation.html');
exit();
К
// Pear Mail Library
require_once "Mail.php";
$from = '<[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 {
header('Location: confirmation.html');
exit();
}
Вот ссылка на почтовую библиотеку груши.
http://pear.php.net/package/Mail/docs
Спасибо за решение, брат. Дай мне попробовать. Только один вопрос, что это за файл «Mail.php»? Нужно ли мне его создавать или можно просто написать на PHP, и код будет работать?
Вам нужно перейти по ссылке, которую я добавил в своем ответе. Это почтовая библиотека php, которую вы должны загрузить и включить в свой файл. Вам будет хорошо идти. Также, если он ответил на ваш основной вопрос, отметьте его как одобренный. :) Спасибо @JayT.
Я перешел по ссылке и выполнил указанные шаги, но при отправке формы появляется ошибка ниже: www.example.com в настоящее время не может обработать этот запрос. ОШИБКА HTTP 500
Вам нужно изменить $ myemail на действительный адрес электронной почты в своем скрипте, чтобы вы могли получать электронное письмо.
Итак, в основном вы хотите отправлять письма с помощью своего PHP-приложения, содержащего информацию, введенную вашим пользователем. Я думаю, что ваш код работает нормально. Но вам, вероятно, понадобится библиотека почтовой программы, такая как PHPMailer, чтобы заменить
mail()по умолчанию, чтобы вы могли использовать SMTP-сервер. Взгляните на аналогичную проблему здесь: stackoverflow.com/questions/14456673/…