| 1 |
<?php |
| 2 |
|
| 3 |
namespace EmailKit\Admin\Api; |
| 4 |
|
| 5 |
defined( 'ABSPATH' ) || exit; |
| 6 |
|
| 7 |
class TestEmail { |
| 8 |
|
| 9 |
public $prefix = ''; |
| 10 |
public $param = ''; |
| 11 |
public $request = null; |
| 12 |
public function __construct() { |
| 13 |
|
| 14 |
add_action('rest_api_init', function () { |
| 15 |
register_rest_route('emailkit/v1', 'send-test-email', array( |
| 16 |
'methods' => \WP_REST_Server::ALLMETHODS, |
| 17 |
'callback' => [$this, 'sendEmail'], |
| 18 |
'permission_callback' => '__return_true', |
| 19 |
)); |
| 20 |
}); |
| 21 |
} |
| 22 |
|
| 23 |
public function sendEmail($request) |
| 24 |
{ |
| 25 |
if (!wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest')) { |
| 26 |
return [ |
| 27 |
'status' => 'fail', |
| 28 |
'message' => [__('Nonce mismatch.', 'emailkit')] |
| 29 |
]; |
| 30 |
} |
| 31 |
|
| 32 |
if (!is_user_logged_in() || !current_user_can('publish_posts')) { |
| 33 |
return [ |
| 34 |
'status' => 'fail', |
| 35 |
'message' => [ __('Access denied.', 'emailkit')] |
| 36 |
]; |
| 37 |
} |
| 38 |
|
| 39 |
$post_id = $request->get_param('post_id'); |
| 40 |
$from = get_option('admin_email'); |
| 41 |
$to = $request->get_param('email'); |
| 42 |
|
| 43 |
$pre_header = get_post_meta($post_id, 'emailkit_email_preheader', true); |
| 44 |
$pre_header = !empty($pre_header) ? $pre_header : esc_html__('This is a test email.', 'emailkit'); |
| 45 |
$subject = get_post_meta($post_id, 'emailkit_email_subject', true); |
| 46 |
$subject = !empty($subject) ? $subject . ' - ' . $pre_header : $request->get_param('subject') . ' - ' . $pre_header; |
| 47 |
|
| 48 |
$message = $request->get_param('message'); |
| 49 |
$headers = [ |
| 50 |
'From: ' . $from . "\r\n", |
| 51 |
'Reply-To: ' . $from . "\r\n", |
| 52 |
'Content-Type: text/html; charset=UTF-8', |
| 53 |
]; |
| 54 |
|
| 55 |
$sent = wp_mail($to, $subject, $message, $headers); |
| 56 |
|
| 57 |
if(!$sent){ |
| 58 |
$error_message = error_get_last(); |
| 59 |
$error_message = str_contains($error_message['message'] ?? '', 'Failed to connect to mailserver')? __( 'Failed to connect to mailserver', 'emailkit' ) : __( 'Failed to send the test email.', 'emailkit' ); |
| 60 |
} |
| 61 |
|
| 62 |
|
| 63 |
if ($sent) { |
| 64 |
return [ |
| 65 |
'status' => 'success', |
| 66 |
'message' => [ __( 'Test email sent successfully.', 'emailkit' ) ], |
| 67 |
]; |
| 68 |
} else { |
| 69 |
return [ |
| 70 |
'status' => 'fail', |
| 71 |
'message' => [ esc_html( $error_message) ], |
| 72 |
]; |
| 73 |
} |
| 74 |
} |
| 75 |
} |