Skip to content

Instantly share code, notes, and snippets.

@trev-dev
Last active January 27, 2018 21:16
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 trev-dev/952097e7c799f4d6752c2222427b5837 to your computer and use it in GitHub Desktop.
Save trev-dev/952097e7c799f4d6752c2222427b5837 to your computer and use it in GitHub Desktop.
Simple email mailer
<?php
// $mailer = new Mailer(Obj). Obj is expected to be a parsed JSON object from the front end
// Example {"email": "person@mailing.com", "name": "Person Mailing", "message": "Hello"}
// you decode_json(Obj, true); first before instantiating the mail object with it.
// Mailer will echo a JSON string of either a success message or an array of errors after attempting
// to sanitize, validate and send mail. use $mailer->send(); to run the module after instantiating it.
class Mailer {
function __construct($envelope) {
// Fill out whom this is going to
$this->recipient = 'mailto@email.com';
$this->headers = 'From: website.com <mailer@website.com>';
//Constructed automagically
$this->name = $envelope['name'];
$this->email = $envelope['email'];
$this->message = $envelope['message'];
$this->errors = Array();
}
function sanitize() {
$newLines = '/\\\\r|\\\\n/i';
$this->name = preg_replace($newLines, "", $this->name);
$this->email = preg_replace($newLines, "", $this->email);
$testString = $this->name.$this->email;
$injection = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($injection, $testString)){
array_push($this->errors, (object)['critical'=> 'Header Injection']);
}
}
function validate(){
$this->sanitize();
$fields = array(
"name" => $this->name,
"email" => $this->email,
"message" => $this->message
);
foreach($fields as $key => $value){
switch ($key){
case 'email':
if ($value && filter_var($value, FILTER_VALIDATE_EMAIL) === false){
array_push($this->errors, (object)['email' => $value.' isn\'t a valid email']);
}
default:
if(!$value) {
array_push($this->errors, (object)[$key => 'please provide your '.$key]);
}
}
}
}
function sendMail() {
$subject = $this->name." sent you a message!";
$body = "You received a new message from ".$this->name." (".$this->email.") from justineshu.com!
Message:
".$this->message;
if (mail($this->recipient, $subject, $body, $this->headers)) {
echo json_encode((object)["success" => "Sent"], JSON_UNESCAPED_SLASHES);
} else {
array_push($this->errors, (object)["mailer" => "There was a problem sending the message. Please try again or email info@justineshu.com directly"]);
echo json_encode((object)["errors" => $this->errors], JSON_UNESCAPED_SLASHES);
}
}
function send() {
$this->validate();
if ($this->errors) {
echo json_encode((object)["errors"=> $this->errors], JSON_UNESCAPED_SLASHES);
} else {
$this->sendMail();
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment