PHPMailer 6 Контактная форма с Gmail SMTP - PullRequest
0 голосов
/ 01 июня 2019

Я пытаюсь сделать так, чтобы электронные письма можно было отправлять на мой адрес Gmail, а не на электронную почту моего доменного имени, используя форму PHPMailer, которая находится на сайте Bootstrap.Это моя главная цель, а другая задача - выяснить, как форма должна включать имя человека, адрес электронной почты и тему, которая будет заполнять электронную почту, а не заданную тему и электронную почту «без ответа».Любая помощь, которую я мог бы получить в этом, была бы великолепна;Я думал, что посмотрю, если кто-нибудь захочет решить эту проблему для сообщества, прежде чем я найму фрилансера.Спасибо !!

Я пробовал несколько учебных пособий, чтобы решить эту проблему, а также пытался объединить существующий код, который я публикую ниже, с версией SMTP Gmail на странице PHPMailer Github (https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps)но у меня ничего не получилось, вместо этого я бы отправил здесь рабочий код в электронное письмо с моим доменным именем, чем мои неудачные попытки отправки в Gmail.

    <form id="contact-form" method="post" action="contact.php">

        <div class="messages"></div>
        <div class="controls">

            <div class="form-group">
                <input id="form_name" type="text" name="name" class="form-control" placeholder="Enter your name." required="required">
            </div>

            <div class="form-group">
                <input id="form_email" type="email" name="email" class="form-control" placeholder="Enter your email." required="required">
            </div>

            <div class="form-group">
                <textarea id="form_message" name="message" class="form-control" placeholder="Add your message." rows="4" required="required"></textarea>
            </div>

            <input type="submit" class="btn btn-outline-light btn-sm" value="Send message">

        </div>

    </form>


<?php

use PHPMailer\PHPMailer\PHPMailer;

require './PHPMailer-master/vendor/autoload.php';

$fromEmail = 'noreply@email.com';
$fromName = 'No Reply Email';

$sendToEmail = 'name@mydomain.com';
$sendToName = 'New Website Email Message';

$subject = 'New message from contact form';

$fields = array('name' => 'Name:', 'email' => 'Email:', 'message' => 'Message:');

$okMessage = 'Successfully submitted - we will get back to you soon!';

$errorMessage = 'There was an error while submitting the form. Please try again later';


error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');
    $emailTextHtml .= "<h3>New message from website:</h3><hr>";
    $emailTextHtml .= "<table>";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
        }
    }
    $emailTextHtml .= "</table><hr>";
    $emailTextHtml .= "<p>Have a great day!</p>";

    $mail = new PHPMailer;

    $mail->setFrom($fromEmail, $fromName);
    $mail->addAddress($sendToEmail, $sendToName);
    $mail->addReplyTo($_POST['email'], $_POST['name']);


    $mail->Subject = $subject;

    $mail->Body = $emailTextHtml;
    $mail->isHTML(true);

    if(!$mail->send()) {
        throw new \Exception('Email send failed. ' . $mail->ErrorInfo);
    }

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}


if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}
?>

Ответы [ 2 ]

0 голосов
/ 01 июня 2019

Это работает над моими проектами.Вы также можете удалить ту часть кода, которая вам не нужна, например, вложения.Еще одна вещь, если вы хотите скрыть ошибки кода отладки и уведомления, удалите или прокомментируйте эту строку $ mail-> SMTPDebug = 2. Проверьте эту похожую статью StackOverflow для получения дополнительной помощи

Если вы по-прежнемунужна дополнительная помощь, чтобы сообщить мне.Надеюсь, это поможет вам.


<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'path/to/PHPMailer/src/Exception.php';
require 'path/to/PHPMailer/src/PHPMailer.php';
require 'path/to/PHPMailer/src/SMTP.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    $mail->SMTPDebug = 2;                                 // 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 = 'user@example.com';                 // SMTP username
    $mail->Password = 'secret';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');


    //Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    //Content
    $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';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}`enter code here`
s


0 голосов
/ 01 июня 2019

Это то, что я использую для своей формы почты, измените переменные соответственно.

// PHPMailer
require '/var/www/...../PHPMailer/PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

//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';

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "abcdefgh@gmail.com";

//Password to use for SMTP authentication
$mail->Password = "pppppppppppppppp";

//Set who the message is to be sent from
$mail->setFrom($Email, $Name);

//Set an alternative reply-to address
$mail->addReplyTo($Email, $Name);

//Set who the message is to be sent to
$mail->addAddress('myemailaddress@gmail.com', 'Form Mail');

//Set the subject line
$mail->Subject = 'Form Mail";
// END PHP Mailer
$mail->ContentType = 'text/plain';
$mail->isHTML(false);

// $mail->msgHTML("$Message");

$mail->Body = $Message;
//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Thank you for sending your message.";
}
...