PHP SMTP Email Template

<?php header("Access-Control-Allow-Origin: *"); $rest_json = file_get_contents("php://input"); $_POST = json_decode($rest_json, true); // Get post data $isSecure = $_POST['isSecure']; $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // 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 'phpmailer/src/PHPMailer.php'; require 'phpmailer/src/SMTP.php'; require 'phpmailer/src/Exception.php'; // Initiate new PHPMailer instance. Passing `true` enables exceptions $mail = new PHPMailer(true); try { //Server settings $mail->SMTPDebug = 0; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'mail.test.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'test@test.com'; // SMTP username $mail->Password = 'test'; // SMTP password $mail->SMTPSecure = 'tsl'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to //Recipients $mail->setFrom($email, $name); $mail->addAddress('test@test.com', 'Test'); // Add a recipient $mail->addReplyTo($email, $name); $mail->addCC('cc@example.com'); $mail->addBCC('bcc@example.com'); //Attachments $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name // Define email body message $msg = '<b>Name:</b> ' . $name . '<br />'; $msg .= '<b>Email:</b> ' . $email . '<br />'; $msg .= '<b>Phone:</b> ' . $phone . '<br />'; $msg .= '<b>Message:</b> ' . $message; //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Test Subject'; // Email Subject $mail->Body = $msg; // Email body message $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; // If isSecure is equal to true and exists then send email, otherwise return 404. To stop direct linking and sending emails on page load. if(isset($isSecure) && $isSecure == 'true') { $mail->send(); //echo 'Message has been sent'; echo json_encode(array( "sent" => true )); } else { header("HTTP/1.0 404 Not Found"); } } catch (Exception $e) { //echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo; echo json_encode([ "sent" => false, "message" => "Sorry something went wrong. Message could not be sent. Mailer Error:" ]); } ?>
PHP SMTP Email template to send emails to specified email address. Requires PHP Mailer

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.