The woocommerce_after_shop_loop_item hook has nothing to do with the checkout page but is executed on the shop page, you should instead use a hook that only applies to the checkout page, e.g. woocommerce_before_checkout_form
To avoid error messages, it is best to check whether WC->cart is actually available before using it
So you get:
function action_woocommerce_before_checkout_form() {
// Only logged in users
if ( ! is_user_logged_in() ) return;
// WC Cart
if ( WC()->cart ) {
// Cart NOT empty
if ( ! WC()->cart->is_empty() ) {
// The current user
$current_user = wp_get_current_user();
$email = $current_user->user_email;
$name = $current_user->user_firstname;
// NOT empty
if ( ! empty ( $email ) && ! empty ( $name ) ) {
// The mail structure
$to = $email;
$subject = sprintf( __( 'Hello %s, your message', 'woocommerce' ), $name );
$body = __( 'The mail body', 'woocommerce' );
// Headers
$headers = array( 'Content-Type: text/html; charset=UTF-8' );
// Sends an email, similar to PHP’s mail function
wp_mail( $to, $subject, $body, $headers );
}
}
}
}
add_action( 'woocommerce_before_checkout_form', 'action_woocommerce_before_checkout_form' );
Optional: to send email notifications with the same layout of the other WooCommerce email notifications
Replace
// NOT empty
if ( ! empty ( $email ) && ! empty ( $name ) ) {
// The mail structure
$to = $email;
$subject = sprintf( __( 'Hello %s, your message', 'woocommerce' ), $name );
$body = __( 'The mail body', 'woocommerce' );
// Headers
$headers = array( 'Content-Type: text/html; charset=UTF-8' );
// Sends an email, similar to PHP’s mail function
wp_mail( $to, $subject, $body, $headers );
}
With
// NOT empty
if ( ! empty ( $email ) && ! empty ( $name ) ) {
// Mailer
$mailer = WC()->mailer();
// To, subject, message
$to = $email;
$subject = __( 'My subject', 'woocommerce' );
$message_body = __( 'My message', 'woocommerce' );
// Message head and message body
$message = $mailer->wrap_message( sprintf( __( 'Hello %s', 'woocommerce' ), $name ), $message_body );
// Headers
$headers = 'Content-Type: text/html\r\n';
// Send an email
$mailer->send( $to, $subject, $message, $headers );
}