To generate a test email to a registered user using the WordPress custom endpoint,use this below code
/ Add custom REST API endpoint for sending emails
add_action('rest_api_init', 'register_custom_email_endpoint');
function register_custom_email_endpoint() {
register_rest_route('custom-email/v1', '/send-email/', array(
'methods' => 'POST',
'callback' => 'send_email',
'permission_callback' => '__return_true', // No permission check for simplicity
));
}
// Callback function for the custom endpoint
function send_email($data) {
// Get email and message from the request body
$to_email = sanitize_email($data['to_email']);
$message = sanitize_text_field($data['message']);
// Check if email and message are provided
if (empty($to_email) || empty($message)) {
return new WP_Error('missing_params', 'Email and message are required.', array('status' => 400));
}
// Attempt to send the email
$subject = 'Custom Email';
$headers = array('Content-Type: text/html; charset=UTF-8');
$sent = wp_mail($to_email, $subject, $message, $headers);
// Check if the email was sent successfully
if ($sent) {
return array('status' => 'success', 'message' => 'Email sent successfully.');
} else {
return new WP_Error('email_failed', 'Failed to send email.', array('status' => 500));
}
}