Skip to content

Instantly share code, notes, and snippets.

@minhphong306
Created March 25, 2024 05:05
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 minhphong306/bc551fcc9287f4b4826e152d50d78c6d to your computer and use it in GitHub Desktop.
Save minhphong306/bc551fcc9287f4b4826e152d50d78c6d to your computer and use it in GitHub Desktop.
send_mail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Setting response header json
header('Content-Type: application/json');
// Check if not post method -> throw error
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit();
}
// Decode json body
$body = json_decode(file_get_contents('php://input'), true);
// Check if missing email -> throw error
if (!isset($body['email'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing email']);
exit();
}
// Check if missing subject -> throw error
if (!isset($body['subject'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing subject']);
exit();
}
// Check if missing message -> throw error
if (!isset($body['message'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing message']);
exit();
}
try {
// if (isset($_POST['submit'])) {
$mailData = [
'email' => $body['email'],
'subject' => $body['subject'],
'message' => $body['message']
];
require 'vendor/autoload.php';
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'youremail@gmail';
$mail->Password = 'app_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('fromemail', "Minh Phong 306 Blog");
$mail->addAddress($mailData['email'], 'User');
$mail->isHTML(true);
$mail->Subject = $mailData['subject'];
$mail->Body = $mailData['message'];
$mail->AltBody = 'Alt body';
$mail->send();
echo json_encode(['message' => 'Message has been sent']);
// }
} catch (Exception $ex) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment