首页 > 解决方案 > 带有 Gmail SMTP 的 PHPMailer 6 联系表

问题描述

我正在尝试使用 Bootstrap 网站中的 PHPMailer 表单将电子邮件发送到我的 Gmail 地址,而不是我的域名电子邮件。这是我的主要目标,另一个是弄清楚如何让表单包含人的姓名、电子邮件和填充电子邮件的主题,而不是设置主题和“无回复”电子邮件。我能得到的任何帮助都会很棒;我想在聘请自由职业者之前,我会看看是否有人愿意为这里的社区解决这个问题。谢谢!!

我尝试了几个教程来解决这个问题,并尝试将我在下面发布的现有代码与 PHPMailer Github 页面上的 SMTP Gmail 版本(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'];
}
?>

标签: phpformsphpmailercontacts

解决方案


它正在处理我的项目。您还可以删除不需要的代码部分,例如附件。还有一件事,如果你想隐藏调试代码错误和通知删除或评论这一行 $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



推荐阅读