Skip to content

Instantly share code, notes, and snippets.

@franckweb
Created July 6, 2022 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franckweb/a98da56fde7549aaab1bcba1650a9b4c to your computer and use it in GitHub Desktop.
Save franckweb/a98da56fde7549aaab1bcba1650a9b4c to your computer and use it in GitHub Desktop.
Form Submission with Validation and Email Delivery through SMTP
<section class="contactForm">
<form method="post" action="process">
<div class="row">
<div class="col-6">
<input type="text" name="demo-name" id="demo-name" value="" placeholder="Name">
</div>
<div class="col-6">
<input type="email" name="demo-email" id="demo-email" value="" placeholder="Email">
</div>
<div class="col-12">
<div class="textarea-wrapper">
<textarea name="demo-message" id="demo-message" placeholder="Message" rows="1"></textarea>
</div>
</div>
<div class="col-12">
<ul class="actions">
<li><input type="submit" value="Ok" class="primary js-submit-form"></li>
<li><input type="reset" value="Reset" class="primary js-reset-form"></li>
<li><span class="process_response"></span></li>
</ul>
</div>
</div>
</form>
</section>
<?php
namespace App;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
class Mailer
{
private $client;
private $name;
private $email;
private $subject;
private $content;
private $loginUser = 'loginUser@myDomain.com';
private $loginPassword = 'myPassword';
private $SMTPServer = 'myMailServer.com';
private $sentTo = 'info@myDomain.com';
public function __construct($name, $email, $subject, $content)
{
$this->client = new PHPMailer();
$this->name = $name;
$this->email = $email;
$this->subject = $subject;
$this->content = $content;
}
public function setup()
{
//Tell PHPMailer to use SMTP
$this->client->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$this->client->SMTPDebug = env('APP_DEBUG') ? SMTP::DEBUG_SERVER : SMTP::DEBUG_OFF;
//Set the hostname of the mail server
$this->client->Host = $this->SMTPServer;
//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$this->client->Port = 587;
//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$this->client->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
//Whether to use SMTP authentication
$this->client->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$this->client->Username = $this->loginUser;
//Password to use for SMTP authentication
$this->client->Password = $this->loginPassword;
//Set who the message is to be sent from
//Note that with gmail you can only use your account address (same as `Username`)
//or predefined aliases that you have configured within your account.
//Do not use user-submitted addresses in here
$this->client->setFrom($this->email, 'Sent from myDomain.com');
//Set an alternative reply-to address
//This is a good place to put user-submitted addresses
$this->client->addReplyTo($this->email, $this->name);
//Set who the message is to be sent to
$this->client->addAddress($this->sentTo, 'myDomain.com');
//Set the subject line
$this->client->Subject = $this->subject;
$this->client->Body = <<<EOT
Email: {$this->email}
<br>Name: {$this->name}
<br>Message: {$this->content}
EOT;
//Replace the plain text body with one created manually
$this->client->AltBody = $this->content;
}
public function send()
{
if (!$this->client->send()) {
// echo 'Mailer Error: ' . $this->client->ErrorInfo;
return false;
}
return true;
}
}
<?php
namespace App;
class Process
{
public function contactezNous()
{
$params['demo-name'] = $this->protectHtml($this->request['demo-name']);
$params['demo-email'] = $this->protectHtml($this->request['demo-email']);
$params['demo-message'] = $this->protectHtml($this->request['demo-message']);
$params['subject'] = 'Contactez Nous Request';
$params['description'] = <<<DESCRIPTION
{$params['demo-message']}
DESCRIPTION;
// if given data is not empty
if (
empty($params["demo-name"]) ||
empty($params["demo-email"]) ||
empty($params["demo-message"])
) {
$response = new Response('error', null, "Invalid input request");
return false;
}
// validate fields length
if (
strlen($params['demo-name']) > 50 ||
strlen($params['demo-email']) > 200
) {
$response = new Response('error', null, "Invalid input request.");
return false;
}
// validate demo-email
if (filter_var($params['demo-email'], FILTER_VALIDATE_EMAIL) === false) {
$response = new Response('error', null, "Invalid email address.");
return false;
}
return $this->process($params);
}
public function process($params)
{
$name = $params['demo-name'];
$email = $params["demo-email"];
$subject = $params["subject"];
$content = $params["description"];
// send email
$mailer = new Mailer($name, $email, $subject, $content);
$mailer->setup();
if (!$mailer->send()) {
$response = new Response('error', null, "Message could not be delivered.");
return false;
}
// if message was sent successfully
$response = new Response('success', null, "Thank you for your message.");
return false;
}
public function protectHtml($var)
{
if(empty($var)){
return '';
}
return htmlspecialchars(trim($var), ENT_QUOTES, "UTF-8");
}
}
<script>
$( document ).ready(function() {
$(document).on('click', '.contactForm .js-reset-form', function(e){
$('.js-submit-form').prop('disabled', false);
});
$(document).on('click', '.contactForm .js-submit-form', function(e){
e.preventDefault();
$('.js-submit-form').prop('disabled', true);
var frm = $('.contactForm form');
if(isValidForm(frm, $('.process_response_msg'))){
$.ajax({
type: 'post',
url: 'contact-form-process',
data: frm.serialize(),
dataType: 'json',
success: function (response) {
$('.process_response_msg').html(response.message);
if(response.status === 'error'){
$('.js-submit-form').prop('disabled', false);
}
},
error: function (response) {
$('.process_response_msg').html(response.message);
},
});
} else {
$('.js-submit-form').prop('disabled', false);
}
});
function isValidForm(frm, msgDiv){
var name = frm.find('input[name="demo-name"]').val(),
email = frm.find('input[name="demo-email"]').val(),
message = frm.find('textarea[name="demo-message"]').val();
if(name.length === 0 || email.length === 0 || message.length === 0){
msgDiv.html("all fields are mandatory");
return false;
}
if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email)){
msgDiv.html("enter valid email");
return false;
}
if(!(/^[a-zA-Z]{1,}$/).test(name)){
msgDiv.html("enter a single word name");
return false;
}
return true;
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment