#43349 closed feature request (wontfix)
WP Rest API: Support for WP Mail
Reported by: | bhubbard | Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | 5.1 |
Component: | REST API | Keywords: | |
Focuses: | rest-api | Cc: |
Description
I think it would be great to see rest api support for WP Mail. Here is some sample code I have working to demonstrate.
<?php /** * Rest Routes initialization class. */ class WP_Mail_REST_API { /** * Create the rest API routes. * * @access public * @return void */ public function __construct() { add_action( 'rest_api_init', function(){ register_rest_route( 'mail/v1', 'send', array( 'methods' => array( 'get', 'post' ), 'callback' => array( $this, 'send_email' ), 'permission_callback' => array( $this, 'permission_check' ), 'args' => array( 'to' => array( 'required' => true, 'default' => '', 'description' => 'Array or comma-separated list of email addresses to send message.', 'type' => 'string', ), 'subject' => array( 'required' => true, 'default' => '', 'description' => 'Email subject', 'type' => 'string', ), 'message' => array( 'required' => true, 'default' => '', 'description' => 'Message contents', 'type' => 'string', ), 'headers' => array( 'required' => false, 'default' => '', 'description' => 'Additional headers.', 'type' => 'string', ), 'attachments' => array( 'required' => false, 'default' => '', 'description' => 'Files to attach.', 'type' => 'string', ), ), )); }); } /** * send_email function. * * @access public * @param WP_REST_Request $request * @return void */ public function send_email( WP_REST_Request $request ) { $to = $request['to']; $subject = $request['subject']; $message = $request['message']; $headers = $request['headers']; $attachments = $request['attachments']; $response = wp_mail( $to, $subject, $message, $headers, $attachments ); return rest_ensure_response( $response ); } /** * Check whether the function is allowed to be run. * * Must have either capabilities to enact action, or a valid nonce. * * @param [type] $data [description] * @return [type] [description] */ public function permission_check( $data ) { if ( ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'forbidden', 'You are not allowed to do that.', array( 'status' => 403 ) ); } return true; } } new WP_Mail_REST_API();
Change History (4)
This ticket was mentioned in Slack in #core-restapi by timothybjacobs. View the logs.
7 years ago
Note: See
TracTickets for help on using
tickets.
The WP REST API is designed to model "resources" that you can interact with through a CRUD interface using the HTTP verbs.
Sending one email is difficult to map onto this design, as it is a one-off action, and the actual resource can never be retrieved or linked to.
So the problem for making wp_mail accessible through the REST API lies in defining how to model an email as a resource that fits that design.