send_mail() {
    local to="$1"
    local subject="$2"
    local body="$3"
    local mail_backend="none"

    # Détection du backend
    if command -v mail >/dev/null 2>&1; then
        mail_backend="mail"
    elif command -v sendmail >/dev/null 2>&1; then
        mail_backend="sendmail"
    elif command -v msmtp >/dev/null 2>&1; then
        mail_backend="msmtp"
    fi

    case "$mail_backend" in
        mail)
            echo "$body" | mail -s "$subject" "$to"
            ;;
        sendmail|msmtp)
            {
                echo "To: $to"
                echo "Subject: $subject"
                echo "Content-Type: text/plain; charset=UTF-8"
                echo ""
                echo "$body"
            } | "$mail_backend" -t
            ;;
        *)
            msg_error "No mail system found (mail, sendmail or msmtp)"
            return 1
            ;;
    esac
}

send_login_mail() {

  if [[ ${HAS_WELCOME_CONF_ERROR} -eq 1 ]]; then
    return;
  fi

  if [[ -z "${ADMIN_MAIL}" ]]; then
      msg_error "ADMIN_MAIL [${ADMIN_MAIL}] is not defined in /etc/environment"
      # shellcheck disable=SC2034
      HAS_WELCOME_CONF_ERROR=1
      return 1 # ou exit 1 selon si c'est dans une fonction ou un script
  fi
    # Protection contre les appels multiples
    if [[ ${CON_MAIL_DONE:-0} -eq 1 ]]; then
        return
    fi
    export CON_MAIL_DONE=1

    local user_ip="$1"
    local user_name="$2"
    local host_name="$3"
    local loc_info subject body

    # Capture de la localisation
    loc_info=$(getIpLocation "$user_ip")

    subject="[INFO] $user_name connected on $host_name"
    body="User: $user_name
Host: $host_name
IP: $user_ip
Location: $loc_info
Date: $(date '+%Y-%m-%d %H:%M:%S')"

    send_mail "$ADMIN_MAIL" "$subject" "$body"
}