带有Gmail SMTP的PHPMailer 6联系人表单

时间:2019-05-31 23:55:13

标签: php forms phpmailer contacts

我正在努力做到这一点,以便可以使用Bootstrap网站中的PHPMailer表单将电子邮件发送到我的Gmail地址,而不是域名电子邮件。这是我的主要目标,另一个是弄清楚如何使表格包含人员的姓名,电子邮件以及填充电子邮件的主题,而不是设置的主题和“无回复”的电子邮件。我对此能获得的任何帮助都会很棒。我以为在雇用自由职业者之前,是否会有人愿意为社区解决这个问题。谢谢!

我尝试了一些教程来解决此问题,并尝试将下面发布的现有代码与PHPMailer Github页面(https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps)上的SMTP Gmail版本结合使用,但是我没有成功,我而不是将尝试发送到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 :(得分:0)

这是我用于表格邮件的内容,请相应地更改变量。

// 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.";
}

答案 1 :(得分:0)

它正在处理我的项目。您也可以删除不需要的代码部分,例如附件。如果您想隐藏调试代码错误,并且通知删除或注释此行$ mail-> SMTPDebug = 2,则还有另一件事。 Check this similar StackOverflow article for more help

如果您仍然需要更多帮助让我知道。 希望对您有帮助。

 context.load_cert_chain(certfile=client_cert, keyfile=clients_key, 
 password=None)
 ssl.SSLError: [SSL] PEM lib (_ssl.c:3837)