wp_mail() is the WordPress function for sending email. It works with any SMTP plugin and respects all the mail filters, so always use it instead of the plain PHP mail() function.

Send a simple HTML email

function lotgrafix_send_email( $to, $name ) {
    if ( ! is_email( $to ) ) {
        return false;
    }

    $subject = __( 'Welcome to our site', 'lotgrafix' );
    $body    = '<h2>Hello ' . esc_html( $name ) . '</h2><p>Thanks for contacting us.</p>';
    $headers = array(
        'Content-Type: text/html; charset=UTF-8',
        'From: Lotgrafix <no-reply@yourdomain.com>',
        'Reply-To: Support <support@yourdomain.com>',
    );

    return wp_mail( $to, $subject, $body, $headers );
}

Send to several recipients with an attachment

$lotgrafix_to = array( 'one@example.com', 'two@example.com' );
$lotgrafix_attachments = array( WP_CONTENT_DIR . '/uploads/report.pdf' );

wp_mail( $lotgrafix_to, 'Monthly report', 'Report attached.', '', $lotgrafix_attachments );

Handle a simple contact form

function lotgrafix_handle_contact() {
    check_admin_referer( 'lotgrafix_contact', 'lotgrafix_contact_nonce' );

    $name    = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
    $email   = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
    $message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';

    if ( $name && is_email( $email ) && $message ) {
        wp_mail(
            get_option( 'admin_email' ),
            'New message from ' . $name,
            $message,
            array( 'Reply-To: ' . $name . ' <' . $email . '>' )
        );
    }

    wp_safe_redirect( add_query_arg( 'sent', '1', wp_get_referer() ) );
    exit;
}
add_action( 'admin_post_nopriv_lotgrafix_contact', 'lotgrafix_handle_contact' );
add_action( 'admin_post_lotgrafix_contact', 'lotgrafix_handle_contact' );

The form must post to admin-post.php and include a hidden field named action with the value lotgrafix_contact.

Tips for emails that arrive

  • By default WordPress sends mail from the web server, which often ends up in spam. Use an SMTP plugin with your email provider.
  • The From address should use your own domain and have SPF, DKIM and DMARC records.
  • Put the visitor email in Reply-To, not in From.
  • Check the return value. false means WordPress could not send the message.
«
»