# Email Users When They Log In From a New Device

> Sends members an email when their account is used from a browser and network it has not seen before, so they can react quickly if it was not them.

- Type: PHP
- Runs: Run everywhere
- Category: [Login](https://wpide.com/library/category/login/)
- Tags: login, security, email
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/new-device-login-alert/

## Code

```php
// How many known devices to remember per user.
$wpide_known_devices = 10;

add_action( 'wp_login', function ( $login, $user ) use ( $wpide_known_devices ) {
    $ip  = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
    $ua  = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
    // Use the network part of the IP so a changing last digit does not count as new.
    $net = preg_replace( '/\.\d+$/', '', $ip );
    $key = wp_hash( $net . '|' . $ua );

    $known = get_user_meta( $user->ID, 'wpide_known_devices', true );
    $first = ! is_array( $known );
    $known = $first ? array() : $known;

    if ( in_array( $key, $known, true ) ) {
        return;
    }

    array_unshift( $known, $key );
    update_user_meta( $user->ID, 'wpide_known_devices', array_slice( $known, 0, $wpide_known_devices ) );

    if ( $first ) {
        return;
    }

    wp_mail(
        $user->user_email,
        sprintf( '[%s] New login to your account', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ),
        sprintf(
            "Hi %s,\n\nYour account was just used to log in from a new device.\n\nTime: %s\nIP address: %s\nBrowser: %s\n\nIf this was you, there is nothing to do. If not, reset your password now:\n%s",
            $user->display_name,
            wp_date( 'Y-m-d H:i' ),
            $ip,
            $ua,
            wp_lostpassword_url()
        )
    );
}, 10, 2 );
```

## Notes

The first login after activation is remembered without an email. Only a hash of the browser and network is stored, not the full IP address.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Email Users When They Log In From a New Device" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
